我想在文本文件的每一行的每个开头和结尾添加一些字符/文本,例如
Hi there
Welcome
到
sometext Hi there sometext
sometext Welcome sometext
由于
答案 0 :(得分:3)
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("newfile.txt"), true));
String strLine;
while ((strLine = br.readLine()) != null) {
bw.write("someText" + strLine + "someText");
bw.newLine();
}
bw.close();
in.close();
答案 1 :(得分:3)
StringBuilder result = new StringBuilder();
org.apache.commons.io.LineIterator it = org.apache.commons.io.FileUtils.lineIterator(file);
try {
while (it.hasNext()) {
String line = it.nextLine();
result.append("sometext ").append(line).append(" sometext\n")
}
} finally {
it.close();
}
org.apache.commons.io.FileUtils.writeStringToFile(outFile, result.toString());
答案 2 :(得分:1)
您可以使用Java的String.format
方法。当您使用BufferedReader的ReadLine
方法读取文本文件时,只需在行上调用String.format