java – 将换行符写入文件
发布时间:2020-12-14 05:28:07 所属栏目:Java 来源:网络整理
导读:考虑以下功能 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.
考虑以下功能
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |