考虑以下功能
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(); }
添加什么来使它每次写在下一行?
例如,我想要一个给定字符串的单词在一个单独的lline例如:
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