I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.
import java.io.PrintWriter; import java.io.File; public class Testing { public static void main(String[] args) { File file = new File ("C:/Users/Me/Desktop/directory/file.txt"); PrintWriter printWriter = new PrintWriter ("file.txt"); printWriter.println ("hello"); printWriter.close (); } }
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
The constructor creates an object for the file and also creates a disk file: PrintWriter output = new PrintWriter( "myOutput. txt" ); If the file already exists its contents will be destroyed unless the user does not have permission to alter the file.
PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With