Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PrintWriter and File classes in Java?

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 ();          } } 
like image 658
SPARK Avatar asked Jul 16 '12 00:07

SPARK


People also ask

What is the use of PrintWriter class in Java?

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.

Will PrintWriter create a file?

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.

Which method do we call from the PrintWriter class to write text to a file?

PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method.


Video Answer


1 Answers

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); 
like image 199
Jack Avatar answered Sep 20 '22 04:09

Jack