Append a character at each beginning and end of line in a file using Java

家住魔仙堡 提交于 2019-12-11 12:28:13

问题


can you help me with this problem.

I want to put some characters/text at every beginning and end of each line in my text file e.g.

Hi there
Welcome

to

sometext Hi there sometext
sometext Welcome sometext

Thanks


回答1:


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:


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();



回答3:


You could use Java's String.format method.

When you read the textfile with, say, a BufferedReader's ReadLine method just call String.format on the line.



来源:https://stackoverflow.com/questions/7173361/append-a-character-at-each-beginning-and-end-of-line-in-a-file-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!