如何使用 Java 将文件的内容另存为单个字符串



我正在尝试使用分隔符从文本文件中提取特定内容。这是我的代码:

File file = new File("C:\Inputfiles\message.txt"); 
BufferedReader br = new BufferedReader(new FileReader(file)); 
String st; 
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}

但结果是,每一行都被分隔符分割并保存为数组。

谁能建议如何将文件中的内容保存为单个字符串,这样我只能将有限数量的行作为数组。

您可以使用StringBuilderStringBuffer来执行此操作。

File file = new File("C:\Inputfiles\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
StringBuilder singleString = new StringBuilder();
for(String s : strings){
singleString.append(s);
}
System.out.println(singleString.toString());
}

谢谢大家,

我使用了以下更改

String contents = new String(Files.readAllBytes(Paths.get("C:\Inputfiles\message1.txt")));
String[] splitted = StringUtils.split(contents, "-------");
for(int i=0;i<splitted.length;i++)
System.out.println(splitted[i]);

最新更新