简体   繁体   中英

How come this method does not open up a file and write to it?

I made this method and my goal is to populate a txt file of name filename with the elements that are contained in arrayToWrite, but it does not seem to be working. Does the file get deleted once the method ends? because that is my main issue it would seem my other method can not print the content that is in the file made by this method.

public static void writeFile(String[] arrayToWrite, String filename) throws IOException{
    FileOutputStream fileStream = new FileOutputStream(filename);
    PrintWriter outFS = new PrintWriter(fileStream);

    for (int i = 0; i < arrayToWrite.length; i++) {
        outFS.println(arrayToWrite[i]);
    }
}

Add an outFS.close() to the end of your function.

You may declare one or more resources in a try-with-resources statement and both FileOutputStream class and PrintWriter class implement the AutoCloseable interface, so to solve your problem you can write:

public static void writeFile(String[] arrayToWrite, String filename) throws IOException {
    try (
      FileOutputStream fileStream = new FileOutputStream(filename);
      PrintWriter outFS = new PrintWriter(fileStream)
    ) {  

        for (int i = 0; i < arrayToWrite.length; i++) {
            outFS.println(arrayToWrite[i]);
        }

    }
}

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