Pages

Wednesday, December 1, 2021

How to use PrintWriter and File classes in Java?

1. Overview

In this tutorial, We'll learn how to use PrintWriter class along with the File api classes in java.

In the previous article, we've shown what are the methods of PrintWriter and their examples.

If you want to write some contents to the file using printwriter then you need to make sure the file path given must exist else will get a file not found exception at the runtime.

In this post, we will show you how to always the directory and file is available to the printwriter and avoid errors.

Let us write a few examples to understand the file handling with PrintWriter.


How to use PrintWriter and File classes in Java?



2. Use PrintWriter write to File - when Folder exists


Let us create a simple example program to demonstrate to write the contents to file when the given folder exists.

Example 1

package com.javaprogramto.files.printwriter.tofile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintWriterToFileExample1 {

	public static void main(String[] args) throws FileNotFoundException {
		
		File file = new File("src/main/resources/print_writer/test2.txt");
		
		PrintWriter writer = new PrintWriter(file);
		
		writer.println("Line 1");
		writer.println("Line 2");
		writer.println("Line 3");
		
		writer.flush();
		
		writer.close();
		System.out.println("Done");

	}

}

Output

Contents are written to the file.

Use PrintWriter write to File




3. Use PrintWriter write to File - When Folder Not Exists


When the folder is present, the program is executed successfully with no errors. But what happens when provided file path does not exist?

Here the path is added with folder "file" which is physical does not exist.

Example 2

package com.javaprogramto.files.printwriter.tofile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintWriterToFileExample2 {

	public static void main(String[] args) throws FileNotFoundException {
		
		File file = new File("src/main/resources/print_writer/file/test2.txt");
		
		PrintWriter writer = new PrintWriter(file);
		
		writer.println("Line 1");
		writer.println("Line 2");
		writer.println("Line 3");
		
		writer.flush();
		
		writer.close();
		System.out.println("Done");

	}

}

Output

Exception in thread "main" java.io.FileNotFoundException: src/main/resources/print_writer/file/test2.txt (No such file or directory)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:234)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
	at java.base/java.io.PrintWriter.<init>(PrintWriter.java:309)
	at com.javaprogramto.files.printwriter.tofile.PrintWriterToFileExample2.main(PrintWriterToFileExample2.java:13)

So, when the folder is not created already then this program ended up in the error.


4. Use PrintWriter write to File - Create Folder Programmatically


So now when the folder is not created it terminates the application with an error.

Now, we want to create the missing folders dynamically at runtime. File API has few utility methods that handle the folder creation if it does not exist.

Use File.getParentFile().mkdirs() method to create the missing folders.


Example 3
package com.javaprogramto.files.printwriter.tofile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintWriterToFileExample3 {

	public static void main(String[] args) throws FileNotFoundException {
		
		File file = new File("src/main/resources/print_writer/file/test2.txt");
		file.getParentFile().mkdirs();
		
		PrintWriter writer = new PrintWriter(file);
		
		writer.println("Line 1");
		writer.println("Line 2");
		writer.println("Line 3");
		
		writer.flush();
		
		writer.close();
		System.out.println("Done");

	}
}

Look at the below image, we do not have the folder with the name "file" in the directory src/main/resources/print_writer/.

file folder does not exist




Output

Run this program and see the output below to see this throws the exception or not.


creating missing folders using file api mkdirs()

The above code runs successfully and folders are created for missing ones.


5. Use PrintWriter write to File - With File.createNewFile()


You can try using the File class createNewFile() method but this throws the IOException if the folder does not exist and this method creates only the file but not the missing folder.

Example 4

File file = new File("src/main/resources/print_writer/file/test2.txt");
		file.createNewFile();

Output
Exception in thread "main" java.io.IOException: No such file or directory
	at java.base/java.io.UnixFileSystem.createFileExclusively(Native Method)
	at java.base/java.io.File.createNewFile(File.java:1027)
	at com.javaprogramto.files.printwriter.tofile.PrintWriterToFileExample3.main(PrintWriterToFileExample3.java:13)a
Failed because the folder is not present.


6. Conclusion


In this article, we've seen how to use PrintWriter with File api classes.

Use File.getParentFile().mkdirs() method to get created missing folders.




No comments:

Post a Comment

Please do not add any spam links in the comments section.