Site icon

Write file in java using PrintWriter (class hierarchy & example)

Constructors of PrintWriter (Java IO)

Fig 1: PrintWriter hierarchy

We will write the following kinds of data using PrintWriter:

Program – Write file in java using PrintWriter

package org.learn.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriterDemo {
	public static void main(String[] args) throws IOException {
		writeUsingPrintWriter();
	}

	private static void writeUsingPrintWriter() throws IOException {
		System.out.println("1. Start writting contents to file - PrintWriter");
		try (FileWriter fileWriter = new FileWriter(new File("sampleFile.txt"));
				PrintWriter printWriter = new PrintWriter(fileWriter)) {
			char charValue = 'A';
			boolean booleanValue = false;
			int intValue = 100;
			double doubleValue = 20.15;
			char[] charArray = "CharArray".toCharArray();
			String stringValue = "Some Value";		
			
			//Writing using PrintWriter
			printWriter.print(charValue);
			printWriter.print('.');
			printWriter.write(" Soccer");
			printWriter.println();
			printWriter.print(booleanValue);
			printWriter.println();
			printWriter.println(intValue);
			printWriter.println(doubleValue);
			printWriter.println(charArray);
			printWriter.println(stringValue);
			printWriter.format("Format - StringValue:%s, Integer:%d, char:%c",stringValue,intValue,charValue);
			printWriter.println();
			printWriter.write("Successfully demonstrated PrintWriter");
		}
		System.out.println("2. Successfully written contents to file - PrintWriter");
	}	
}

Output – Write file in java using PrintWriter

1. Start writting contents to file - PrintWriter
2. Successfully written contents to file - PrintWriter
Fig 2: Output of PrintWriter

Oracle Reference

Exit mobile version