如何将文本文件加载到 java 中的字符串变量
How to load a text file to a string variable in java
我是编程界的新手,我找不到关于如何使用 eclpise 在 java 中将 txt 文件加载到字符串变量的很好的解释。
到目前为止,据我所知,我应该使用 StdIn class,并且我知道 txt 文件需要位于我的 eclipse 工作区中(在源文件夹之外) ) 但我不知道我需要在代码中写什么才能让给定的文件加载到变量中。
我真的需要一些帮助。
虽然我不是 Java 专家,但我很确定 this is the information you're looking for 它看起来像这样:
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
将结果的每一行附加到它。
- 读取完成后将结果添加到
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();
}
}
我是编程界的新手,我找不到关于如何使用 eclpise 在 java 中将 txt 文件加载到字符串变量的很好的解释。
到目前为止,据我所知,我应该使用 StdIn class,并且我知道 txt 文件需要位于我的 eclipse 工作区中(在源文件夹之外) ) 但我不知道我需要在代码中写什么才能让给定的文件加载到变量中。
我真的需要一些帮助。
虽然我不是 Java 专家,但我很确定 this is the information you're looking for 它看起来像这样:
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
将结果的每一行附加到它。 - 读取完成后将结果添加到
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();
}
}