关于为何Output Stream仅将转换后的变量的最后一行打印到新文件而不是所有行的解释?

问题描述 投票:0回答:1

我正在尝试将英语单词从文本文件转换为新文件,该文件将单词翻译成Pig Latin。当将其简单地打印到控制台时,所有内容都会转换它应有的方式,但是我遇到的问题是,只有初始文件的最后一行出现在新文件上。

public static void newFile(String pigLatin) {
    OutputStream os = null;
    try {
        os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt"));
        os.write(pigLatin.getBytes(), 0, pigLatin.length());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
java file apache-pig new-operator outputstream
1个回答
0
投票

默认情况下,FileOutputStream会覆盖现有文件。您需要做的是将另一个构造函数与append参数

结合使用
FileOutputStream(String name, boolean append)

like

os = new FileOutputStream(new File("/Users/...", true))

看看reference

© www.soinside.com 2019 - 2024. All rights reserved.