![](/img/trans.png)
[英]how to modify some of the contents of the file and save in the same file using java
[英]how to save contents of a file as single string using 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);}
但結果,每一行都被分隔符分割並保存為數組。
任何人都可以建議我如何將文件中的內容保存為單個字符串,因此我只能將有限數量的行作為 Array.
您可以使用StringBuilder
或StringBuffer
來做到這一點。
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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.