Java中如何使用函数将文本文件读取到字符串中?
发布时间:2023-09-30 08:02:14
在Java中,可以使用以下方法将文本文件读取到字符串中。
1. 使用File类指定要读取的文件路径和名称。
File file = new File("文件路径/文件名.txt");
2. 使用BufferedReader类读取文件内容。
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator()); // 添加换行符
}
String content = stringBuilder.toString();
3. 关闭BufferedReader。
reader.close();
完整的读取文件内容到字符串的函数可以是这样的:
public static String readFileToString(String filePath) throws IOException {
File file = new File(filePath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator()); // 添加换行符
}
reader.close();
return stringBuilder.toString();
}
你可以在项目中调用该函数,并传入要读取的文件路径来获取文件内容的字符串表示。
try {
String content = readFileToString("文件路径/文件名.txt");
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
以上是将整个文件读取到一个字符串中的方法。如果你希望逐行读取文件内容,可以将每行字符串存储在List中。
public static List<String> readFileToList(String filePath) throws IOException {
File file = new File(filePath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
List<String> lines = new ArrayList<>();
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.close();
return lines;
}
调用该函数的方式与前面的方法相同,但返回的是一个包含每行内容的字符串列表。
try {
List<String> lines = readFileToList("文件路径/文件名.txt");
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
以上是在Java中将文本文件读取到字符串的方法,你可以根据自己的需求选择适合的方法来使用。
