IOException is a super class of FileNotFoundException. Therefore your catch block for IOException also catches every FileNotFoundException.

You should implement the function as follows:

public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {

    try (FileWriter writer = new FileWriter(filename)) {
        for (String str : assignment) {
            writer.write(str + "\n");
        }
    } catch (FileNotFoundException e) {
        throw e; // catch and re-throw
    } catch (IOException e) {
        System.err.print("Something went wrong");
    }
}
Answer from JMax on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › putItTogether.html
Putting It All Together (The Java™ Tutorials > Essential Java Classes > Exceptions)
Now that the runtime has found an appropriate handler, the code in that catch block is executed. After the exception handler executes, the runtime system passes control to the finally block. Code in the finally block executes regardless of the exception caught above it. In this scenario, the FileWriter was never opened and doesn't need to be closed.
🌐
Java67
java67.com › 2023 › 01 › how-to-write-file-in-java-with-try.html
How to write to a File with try-with-resource in Java? Example Tutorial | Java67
try (FileWriter writer = new FileWriter("programming.txt"); BufferedWriter bwr = new BufferedWriter(writer);) { You can also see that we can open multiple resources as long as they are separated by semi-colon. If you notice, we only have catch block and there is no finally block in the end because we don't really need any code for closing these resources, they will be automatically be closed when the code inside try block is finished.
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › essential › exceptions › putItTogether.html
Putting It All Together
After the exception handler has executed, the runtime system passes control to the finally block. Code in the finally block executes regardless of the exception caught above it. In this scenario, the FileWriter was never opened and doesnt need to be closed. After the finally block has completed ...
🌐
CodeJava
codejava.net › java-core › exception › what-you-may-not-know-about-the-try-catch-finally-construct-in-java
What you may not know about the try-catch-finally construct in Java
If that happens, the try-catch block exits but the file remains opened as line 4 could not be reached. So a good practice is using the finally block to close the file regardless of exceptions, as shown in the following updated code: FileWriter writer = null; try { writer = new FileWriter("Name.txt"); writer.write("Hello "); //1 String name = args[0]; //2 writer.write(name); //3 writer.close(); //4 } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException ce) { ce.printStackTrace(); } } }
🌐
Stack Abuse
stackabuse.com › the-try-with-resources-statement-in-java
The try-with-resources Statement in Java
April 5, 2019 - The syntax for try-with-resources is almost identical to the usual try-catch-finally syntax. The only difference are the parentheses after try in which we declare which resources we'll be using: BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(fileName)); writer.write(str); // do something with the file we've opened } catch (IOException e) { // handle the exception } finally { try { if (writer != null) writer.close(); } catch (IOException e) { // handle the exception } }
🌐
Tabnine
tabnine.com › home page › code › java › java.io.filewriter
java.io.FileWriter.write java code examples | Tabnine
public static void writeFile(File file, String text, boolean append) throws IOException { if (file == null || text == null) { throw new IllegalArgumentException(); } if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { throw new IOException("Could not create parent directory"); } if (!file.exists() && !file.createNewFile()) { throw new IOException("Could not create file"); } FileWriter writer = null; try { writer = new FileWriter(file, append); writer.write(text); } finally { close(writer); } }
🌐
Program Creek
programcreek.com › 2013 › 12 › should-close-be-put-in-finally-block-or-not
Should .close() be put in finally block or not? – Program Creek
December 19, 2013 - //close() is in finally clause PrintWriter out = null; try { out = new PrintWriter( new BufferedWriter( new FileWriter("out.txt", true))); out.println("the text"); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } }
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 22897968 › using-filewriter-with-try-catch-for-ioexception-with-several-issues
java - Using FileWriter with try catch, for IOException with several issues - Stack Overflow
import java.io.FileWriter.*; import java.io.*; private void ExportGoActionPerformed(java.awt.event.ActionEvent evt) { FileWriter writer; try { writer = new FileWriter("Inventory.txt"); for(String str: Inventory) { writer.write(str); } writer.close(); }catch (IOExeption e){ AlertOut.setText("I'm afraid your file could not be writen at this time."); } finally { try { writer.close(); } catch (IOException ignore){} } public static void main(String args[]) {
Top answer
1 of 2
1

Your problem is this line:

FileWriter fw = new FileWriter(file2);

Constructing the FileWriter is throwing an IOException, and because it is outside your try-Catch block, it isn't being caught. I suggest you try addding it in the following way:

try(FileWriter fw = new FileWriter(file2); BufferedWriter bw = new BufferedWriter(fw);) 
//and then the rest of your try catch block

This turns your try-catch into a try-with-resources block which basically means once the code is block is finished the writers should automatically close

EDIT

If you assign the variables in the try-with-Resources like so:

try(FileWriter fw = new FileWriter(file2); BufferedWriter bw = new BufferedWriter(fw);
    FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis)) {

then you can remove all of these:

// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
bw.flush();
bw.close();

As the try-with-resources can automatically try and close anything within the (at the start to save you trying to do it manually)

2 of 2
0

You have unhandle exception here,Try implement try-catch for it

FileWriter fw = new FileWriter(file2);

can be changed to

  FileWriter fw=null;
     try {
         fw = new FileWriter(file2);
     }catch(IOException e){
         e.printStackTrace();
     }

and you can put these resource close in finally block of respective try-catch-finally. You will also need to check if not null

// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
bw.flush();
bw.close();
fw.close();
🌐
Medium
medium.com › thefreshwrites › try-catch-finally-in-java-exception-handling-2ed273814cd8
Try-Catch-Finally In Java | Exception Handling | by Mouad Oumous | The Fresh Writes | Medium
February 22, 2024 - The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. ... The following finally block for the writeList method cleans up and then closes the PrintWriter and FileWriter.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › ERR54-J.+Use+a+try-with-resources+statement+to+safely+handle+closeable+resources
ERR54-J. Use a try-with-resources statement to safely handle closeable resources | CERT Secure Coding
This noncompliant code example uses an ordinary try - catch - finally block in an attempt to close two resources. ... public void processFile(String inPath, String outPath) throws IOException{ BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(inPath)); bw = new BufferedWriter(new FileWriter(outPath)); // Process the input and produce the output } finally { try { if (br != null) { br.close(); } if (bw != null) { bw.close(); } } catch (IOException x) { // Handle error } } }
🌐
Stack Overflow
stackoverflow.com › questions › 79625684 › my-do-while-loop-wont-write-to-a-file-correctly
try catch finally - My do while loop won't write to a file correctly - Stack Overflow
public static void main(String[] args) { Scanner Test = new Scanner(System.in); String Password; String TruePassword = "1234"; int I = 0; File PassAtm = new File ("Attempted Passwords.txt"); System.out.println ("Password?"); //sets loop in motion do{ Password = Test.nextLine(); try{ try{ //creates and checks to see if new file was created succesfully BufferedWriter FW = new BufferedWriter (new FileWriter("Attempted Passwords.txt")); FW.write (Password ); //checks to see if password is correct if (Password.equals( TruePassword)){ System.out.println ("Nice!"); I = 4; } else { System.out.println ("Dummy."); I++; } } finally { FW.close(); } } catch (IOException E) { }; } while (I < 3); if ( I == 3 ) {System.out.println ("Get outta here, scoundral."); } else if (I == 4) { System.out.println ("Welcome back, Captain."); } } Sorry for the strange formatting, this is my first post.
🌐
Bytearray
bytearray.pub › archives › 11515503.html
Using FileWriter with try catch, for IOException with several issues
import java.io.FileWriter.*; import java.io.*; private void ExportGoActionPerformed(java.awt.event.ActionEvent evt) { FileWriter writer; try { writer = new FileWriter("Inventory.txt"); for(String str: Inventory) { writer.write(str); } writer.close(); }catch (IOExeption e){ AlertOut.setText("I'm afraid your file could not be writen at this time."); } finally { try { writer.close(); } catch (IOException ignore){} } public static void main(String args[]) {
🌐
Coderanch
coderanch.com › t › 404257 › java › close-FileWriter-Object
Do we need to close FileWriter Object??? (Beginning Java forum at Coderanch)
Hello Ranchers For the following code below do we need to close the filewriter object in finally block even when i close BufferedWriter Object. private void appendFile(String fileName) throws IOException{ BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(fileName, true)); String textToFile= "Hello"; bw.write(textToFile); bw.newLine(); bw.flush(); } catch (IOException ioe) { throw ioe; } finally { // close the file if (bw != null)try { bw.close(); } catch (IOException ioe2) { throw ioe2; } } // end try/catch/finally } Suppose you call this method from say a class giving fileName has the input parameter the programs works fine but Occasionally it says Input file opened lot of resources .
🌐
Stack Overflow
stackoverflow.com › questions › 46308333 › append-to-file-with-try-with-resources
java - Append to File With try-with-resources - Stack Overflow
September 20, 2017 - I'm trying to shift from try-catch-finally to try-with-resources but having difficulties applying it for appending line to file (adding a line at the bottom). ... String toAppend = "this is a new line\n"; try (FileWriter fw = new FileWriter("/home/test.txt",true)) { fw.write(toAppend); } catch(IOException ioe) { throw new RehydrateCLIException("Failed to update file", ioe); }
Top answer
1 of 8
60

Note that the following is only applicable for Java 6 and earlier. For Java 7 and later, you should switch to using try-with-resources ... as described in other answers.

If you are trying to catch and report all exceptions at source (in Java 6 or earlier), a better solution is this:

ObjectOutputStream oos = null;
try {
   oos = new ObjectOutputStream(new FileOutputStream(file));
   oos.writeObject(shapes);
   oos.flush();
} catch (FileNotFoundException ex) {
    // complain to user
} catch (IOException ex) {
    // notify user
} finally {
    if (oos != null) {
        try {
            oos.close();
        } catch (IOException ex) {
            // ignore ... any significant errors should already have been
            // reported via an IOException from the final flush.
        }
    }
}

Notes:

  • The standard Java wrapper streams, readers and writers all propagate close and flush to their wrapped streams, etc. So you only need to close or flush the outermost wrapper.
  • The purpose of flushing explicitly at the end of the try block is so that the (real) handler for IOException gets to see any write failures1.
  • When you do a close or flush on an output stream, there is a "once in a blue moon" chance that an exception will be thrown due to disc errors or file system full. You should not squash this exception!.

If you often have to "close a possibly null stream ignoring IOExceptions", then you could write yourself a helper method like this:

public void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

then you can replace the previous finally block with:

} finally {
    closeQuietly(oos);
}

Another answer points out that a closeQuietly method is already available in an Apache Commons library ... if you don't mind adding a dependency to your project for a 10 line method.

But be careful that you only use closeQuietly on streams where IO exceptions really are irrelevant.

UPDATE : closeQuietly is deprecated in version 2.6 of the Apache Commons API. Java 7+ try-with-resources makes it redundant.


On the issue of flush() versus close() that people were asking about in comments:

  • The standard "filter" and "buffered" output streams and writers have an API contract that states that close() causes all buffered output to be flushed. You should find that all other (standard) output classes that do output buffering will behave the same way. So, for a standard class it is redundant to call flush() immediately before close().

  • For custom and 3rd-party classes, you need to investigate (e.g. read the javadoc, look at the code), but any close() method that doesn't flush buffered data is arguably broken.

  • Finally, there is the issue of what flush() actually does. What the javadoc says is this (for OutputStream ...)

    If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

    So ... if you hope / imagine that calling flush() guarantees that your data will persist, you are wrong! (If you need to do that kind of thing, look at the FileChannel.force method ...)

2 of 8
33

Current best practice for try/catch/finally involving objects that are closeable (e.g. Files) is to use Java 7's try-with-resource statement, e.g.:

try (FileReader reader = new FileReader("ex.txt")) {
    System.out.println((char)reader.read());
} catch (IOException ioe) {
    ioe.printStackTrace();
}

In this case, the FileReader is automatically closed at the end of the try statement, without the need to close it in an explicit finally block. There are a few examples here:

http://ppkwok.blogspot.com/2012/11/java-cafe-2-try-with-resources.html

The official Java description is at:

http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

🌐
DigitalOcean
digitalocean.com › community › tutorials › java-filewriter-example
Java FileWriter Example | DigitalOcean
August 4, 2022 - package com.journaldev.io.filewriter; import java.io.FileWriter; import java.io.IOException; /** * Java write file using FileWriter write method * * @author pankaj * */ public class FileWriterWriteIntExample { public static void main(String[] args) { FileWriter fileWriter = null; try { fileWriter = new FileWriter("D:/data/file.txt"); //inherited method from java.io.OutputStreamWriter fileWriter.write(65); fileWriter.write(66); fileWriter.write(67); } catch (Exception e) { e.printStackTrace(); }finally { try { if (fileWriter != null) { fileWriter.flush(); fileWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } }