考虑以下功能
private static void GetText(String nodeValue) throws IOException {
if(!file3.exists()) {
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null)
fop.write(nodeValue.getBytes());
fop.flush();
fop.close();
}
添加什么让它每次都写在下一行?
例如,我希望给定字符串的每个单词都在一个单独的行中,例如:
i am mostafa
写成:
i
am
mostafa
最佳答案
要将文本(而不是原始字节)写入文件,您应该考虑使用 FileWriter .您还应该将其包装在 BufferedWriter 中然后会给你 newLine方法。
要将每个单词写在一个新行上,请使用 String.split将您的文本分解为单词数组。
所以这是对您的要求的简单测试:
public static void main(String[] args) throws Exception {
String nodeValue = "i am mostafa";
// you want to output to file
// BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
// but let's print to console while debugging
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] words = nodeValue.split(" ");
for (String word: words) {
writer.write(word);
writer.newLine();
}
writer.close();
}
输出是:
i
am
mostafa
关于java - 将换行符写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8491687/