将换行符写入文件 [英] write newline into a file
本文介绍了将换行符写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下函数
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();
}
添加什么以使其每次都写入下一行?
what to add to make it to write each time in the next line?
例如我想要一个单独的lline中给定字符串的每个单词,例如:
for example i want each words of a given string in a seperate lline for example:
i am mostafa
写道:
i
am
mostafa
推荐答案
要将文本(而不是原始字节)写入文件,您应该考虑使用 FileWriter 。您还应该将其包装在 BufferedWriter 中然后会给你 newLine 方法。
To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.
要在新行上写下每个单词,请使用 String.split 将文本分成几个单词。
To write each word on a new line, use String.split to break your text into an array of words.
所以这里是对您的要求的简单测试:
So here's a simple test of your requirement:
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
这篇关于将换行符写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文