You can use a try-with-resources block
try (PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(csvFileIn)))) {
//WHATEVER you need to do
}
Since PrintWriter implements AutoCloseable it will close by itself once the try block is complete (even if an exception is raised)
Check more info about this here
Answer from SCouto on Stack OverflowYou can use a try-with-resources block
try (PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(csvFileIn)))) {
//WHATEVER you need to do
}
Since PrintWriter implements AutoCloseable it will close by itself once the try block is complete (even if an exception is raised)
Check more info about this here
You should use -
fileOut.close();
As you do not have any variable name assigned to BufferedWriter or FileWriter also the fileOut is made from them when you close fileOut it will in turn close both the streams.
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
You should try creating a path for the folder it contains before:
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) throws IOException {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
throw an exception for the file.
Yes, closing any Writer/Reader will close all other Writers and Readers that they wrap. Don't close it until you are ready to close the underlying socket.
As @Eddie said (seconds before me! :) ), closing the writer and/or the reader will close the underlying socket streams and the socket itself: However, I believe the socket itself will not be closed.
Closing the returned InputStream will close the associated socket.
You shouldn't close the writer nor the reader. Just flush the writer to make sure your messages will arrive in time. Closing the socket later on will close the respective streams, so you don't need to close them yourself. Just leave your reader/writer objects to the GC.