简体   繁体   中英

Any explanation as to why Output Stream only prints the last line of the translated variable to a new file instead of all the lines?

I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one.

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();
        }
    }
}

By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter

FileOutputStream(String name, boolean append)

like

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

Take a look at the reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM