问题
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