[英]How to load a text file to a string variable in java
我是編程界的新手,我找不到關於如何使用 eclpise 將 txt 文件加載到 java 中的字符串變量的很好的解釋。
到目前為止,據我所知,我應該使用 StdIn class,並且我知道 txt 文件需要位於我的 eclipse 工作區(在源文件夾之外),但我不知道具體是什么我需要編寫代碼來讓給定的文件加載到變量中。
我真的需要一些幫助。
雖然我不是 Java 專家,但我很確定這就是您要查找的信息它看起來像這樣:
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
基本上所有語言都為您提供了一些從您所在的文件系統中讀取的方法。希望這對您有用!
祝你的項目好運!
要讀取文件並將其存儲在String
中,您可以使用String
或StringBuilder
來完成:
FileReader
的構造函數定義BufferedReader
以傳遞文件名並使其准備好從文件中讀取。StringBuilder
到 append 結果的每一行。String
數據中。public static void main(String[] args) {
String data = "";
try {
BufferedReader br = new BufferedReader(new FileReader("filename"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
data = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.