微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.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

原文地址:https://www.jb51.cc/java/122506.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐