使用Java在文件的每个开头和结尾附加一个字符

时间:2011-08-24 09:43:59

标签: java text append

你可以帮我解决这个问题。

我想在文本文件的每一行的每个开头和结尾添加一些字符/文本,例如

Hi there
Welcome

sometext Hi there sometext
sometext Welcome sometext

由于

3 个答案:

答案 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方法。当您使用BufferedReaderReadLine方法读取文本文件时,只需在行上调用String.format