[英]Java. How to add text to each line
我需要在文件中每一行的末尾添加循环文本。
例如,我的文件如下所示:
Adam
Maria
Jon
现在循环,我需要添加下几列,如下所示:
Adam|Kowalski
Maria|Smith
Jon|Jons
第三栏:
Adam|Kowalski|1999
Maria|Smith|2013
Jon|Jons|1983
等等。 如何有效地做到这一点? 我的程序的一个局限性是 ,我不知道要添加的所有新值,我的意思是我无法立即写“ | Kowalski | 1999 ”,而需要写“ | Kowalski”,然后再添加“ | 1999”
谢谢
您可以尝试如下操作:
public static void main(String[] args) throws Exception {// for test I throw the Exception to keep code shorter.
StringBuilder sb = new StringBuilder();
String path = "the/path/to/file";
BufferedReader bReader = new BufferedReader(new FileReader(path));
String line;
while ((line = bReader.readLine()) != null) {
line += "|"+"the-text-to-add"+"\n\r";
sb.append(line);
}
bReader.close();
// now write it back to the file
OutputStream out = new FileOutputStream(new File(path));
out.write(sb.toString().getBytes());
out.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.