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
🌐
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(); } } }
🌐
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.
🌐
Baeldung
baeldung.com › home › java › core java › java – try with resources
Java - Try with Resources | Baeldung
May 11, 2024 - Although the writer variable is not explicitly final, it doesn’t change after the first assignment. So, we can to use the writer variable too. In this article, we discussed how to use try-with-resources and how to replace try, catch, and finally with try-with-resources.
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › essential › exceptions › putItTogether.html
Putting It All Together
Now that the runtime has found an appropriate handler, the code in that catch block is executed. 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 executing, the program continues with the first statement after the finally block. ... Entering try statement Caught IOException: OutFile.txt PrintWriter not open The boldface code in the following listing shows the statements that get executed during this scenario:
Top answer
1 of 1
3

In general, you do not want to upload anything into your application's files - it opens you to many security problems if someone figures out how to overwrite parts of the application, and in most application servers, it is simply not writable.

A much better approach is to have a designated server folder where you can write things. For example, you could have the following in your configuration:

myapp.base-folder = /any/server/folder/you/want

And then, in the code, you would find that folder as follows:

// env is an @AutoWired private Environment
File baseFolder = new File(env.getProperty("myapp.base-folder"));

I find this better than using a database (as @Stultuske suggested in comments), because databases are great for relations, but mostly overkill for actual files. Files can be accessed externally without firing up the database with minimal hassle, and having them separate keeps your database much easier to backup.

To generate links to the file, simply create a link as you would to any other type of request

<a th:href="@{/file/${fileId}|}">Download file</a>

-- and to handle it in the server, but returning the contents of the file:

@GetMapping(value="/file/{id}")
public StreamingResponseBody getFile(@PathVariable long id) throws IOException {        
    File f = new File(baseFolder, ""+id); // numerical id prevents filesytem traversal
    InputStream in;
    if (f.exists()) {
        in = new BufferedInputStream(new FileInputStream(f));
    } else {
        // you could also signal error by returning a 404
        in = new BufferedInputStream(getClass().getClassLoader()
                .getResourceAsStream("static/img/unknown-id.jpg"));
    }
    return new StreamingResponseBody() {
        @Override
        public void writeTo(OutputStream os) throws IOException {
            FileCopyUtils.copy(in, os);
        }
    };
}

I prefer numerical IDs to avoid hassles with path traversal - but you can easily use string filenames instead, and deal with security issues by carefully checking that the canonical path of the requested file starts with the canonical path of your baseFolder

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();
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › java.io.filewriter
java.io.FileWriter.write java code examples | Tabnine
/** * Writes the given text to the file; either in append mode or replace mode depending * the append flag */ public static void write(File file, String text, boolean append) throws IOException { FileWriter writer = new FileWriter(file, append); try { writer.write(text); } finally { writer.close(); } }
🌐
InformIT
informit.com › articles › article.aspx
43. Use a try-with-resources statement to safely handle closeable resources | Java Coding Guidelines for Reliability | InformIT
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 { if (br != null) { try { br.close(); } catch (IOException x) { // Handle error } finally { if (bw != null) { try { bw.close(); } catch (IOException x) { // Handle error } } } } } }
🌐
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 ...
🌐
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 } }
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(); } } } }
🌐
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 } } }