[英]Append a character at each beginning and end of line in a file using Java
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 eg 我想在文本文件的每一行的开始和结尾处都放一些字符/文本,例如
Hi there
Welcome
to 至
sometext Hi there sometext
sometext Welcome sometext
Thanks 谢谢
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();
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());
You could use Java's String.format
method. 您可以使用Java的
String.format
方法。
When you read the textfile with, say, a BufferedReader 's ReadLine
method just call String.format on the line. 例如,当您使用BufferedReader的
ReadLine
方法读取文本文件时,只需在该行上调用String.format。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.