我有這段代碼可以讀取檔案并將內容作為字串回傳,但我不知道將檔案路徑或位置放在哪里
C:\Users\johnm\eclipse-workspace\W4A6\src\input.in
任何幫助都會很棒。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Encryption {
public static String readFile(String filename) throws IOException {
Scanner scanner = new Scanner(new File(filename));
String content = "";
while (scanner.hasNextLine()) {
content = scanner.nextLine();
}
return content;
}
}
uj5u.com熱心網友回復:
問:我把檔案路徑或位置放在哪里?
A:誰呼叫了readFile()你的Encryption類的方法,誰就決定了檔案路徑名。
一種常見的技術是“靜態主”,并將檔案路徑作為命令列引數傳遞。
例子:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Encryption {
public static String readFile(String filename) throws IOException {
Scanner scanner = new Scanner(new File(filename));
String content = "";
while (scanner.hasNextLine()) {
content = scanner.nextLine();
}
return content;
}
public static void main (String[] args) {
if (args.length != 1) {
System.out.println("Please enter a filepath");
} else {
Encryption.readFile(args[0]);
}
}
}
或者,您可以從 GUI 呼叫 Encryption.readFile()。或者來自網路服務。
無論如何:呼叫者應該始終“知道”檔案路徑,并將其作為引數傳遞給 readFile()。
uj5u.com熱心網友回復:
到目前為止,您只定義了一個方法來讀取具有給定檔案名的檔案。
您需要使用您希望的檔案路徑呼叫它,因此在您的情況下:
String content = Encryption.readFile("C:\\Users\\johnm\\eclipse-workspace\\W4A6\\src\\input.in");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321775.html
