$show=/label

Java PrintWriter

SHARE:

A quick guide, how to write the contents into a file in java using PrintWriter class with examples.

1. Overview

In this tutorial, We'll learn how to use PrintWriter class in java with examples.

PrintWriter class is present in a package of java.io and PrintWriter class is an implementation of Writer class.
public class PrintWriter
extends Writer

PrintWriter class is used to store or print the formatted representation of the object to the next output stream.


This class implements all methods from PirntStream class.

None of the methods from PrintWriter class does not throw IOException. But some of the contractors may throw IO Exceptions.

To know the errors are present or not, we need to use the checkError() method.

It is not possible to use PrintWriter with Java 8 Streams.

Java PrintWriter



2. Java PrintWriter Constructors


The below are the constructors of PrintWriter class.


2.1 PrintWriter(File file) throws FileNotFoundException
Creates a new PrintWriter, without automatic line flushing, with the specified file.

2.2 PrintWriter(File file, String csn)  throws FileNotFoundException,UnsupportedEncodingException
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.

2.3 PrintWriter(OutputStream out)
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.

2.4 PrintWriter(OutputStream out, boolean autoFlush)
Creates a new PrintWriter from an existing OutputStream.

2.5 PrintWriter(String fileName)
Creates a new PrintWriter, without automatic line flushing, with the specified file name.

2.6 PrintWriter(String fileName, String csn)
Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.

2.7 PrintWriter(Writer out)
Creates a new PrintWriter, without automatic line flushing.

2.8 PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.


3. Java PrintWriter Methods


Below are 36 useful methods of PrintWriter class.

3.1 PrintWriter append(char c)
Appends the specified character to this writer.

3.2 PrintWriter append(CharSequence csq)
Appends the specified character sequence to this writer.

3.3 PrintWriter append(CharSequence csq, int start, int end)
Appends a subsequence of the specified character sequence to this writer.

3.4 boolean checkError()
Flushes the stream if it's not closed and checks its error state.

3.5 protected void clearError()
Clears the error state of this stream.

3.6 void close()
Closes the stream and releases any system resources associated with it.

3.7 void flush()
Flushes the stream.

3.8 PrintWriter format(Locale l, String format, Object... args)
Writes a formatted string to this writer using the specified format string and arguments.

3.9 PrintWriter format(String format, Object... args)
Writes a formatted string to this writer using the specified format string and arguments.

3.10 void print(boolean b)
Prints a boolean value.

3.11 void print(char c)
Prints a character.

3.12 void print(char[] s)
Prints an array of characters.

3.13 void print(double d)
Prints a double-precision floating-point number.

3.14 void print(float f)
Prints a floating-point number.

3.15 void print(int i)
Prints an integer.

3.16 void print(long l)
Prints a long integer.

3.17 void print(Object obj)
Prints an object.

3.18 void print(String s)
Prints a string.

3.19 PrintWriter printf(Locale l, String format, Object... args)
A convenient method to write a formatted string to this writer using the specified format string and arguments.

3.20 PrintWriter printf(String format, Object... args)
A convenient method to write a formatted string to this writer using the specified format string and arguments.

3.21 void println()
Terminates the current line by writing the line separator string.

3.22 void println(boolean x)
Prints a boolean value and then terminates the line.

3.23 void println(char x)
Prints a character and then terminates the line.

3.24 void println(char[] x)
Prints an array of characters and then terminates the line.

3.25 void println(double x)
Prints a double-precision floating-point number and then terminates the line.

3.26 void println(float x)
Prints a floating-point number and then terminates the line.

3.27 void println(int x)
Prints an integer and then terminates the line.

3.28 void println(long x)
Prints a long integer and then terminates the line.

3.29 void println(Object x)
Prints an Object and then terminates the line.

3.30 void println(String x)
Prints a String and then terminates the line.

3.31 protected void setError()
Indicates that an error has occurred.

3.32 void write(char[] buf)
Writes an array of characters.

3.33 void write(char[] buf, int off, int len)
Writes A Portion of an array of characters.

3.34 void write(int c)
Writes a single character.

3.35 void write(String s)
Writes a string.

3.36 void write(String s, int off, int len)
Writes a portion of a string.


4. Java PrintWriter Example 1 - Writing To Console


The below is a simple program that writes the contents into the console with the help of PrintWriter.write() method and System.out.


Example 1

package com.javaprogramto.files.printwriter;

import java.io.PrintWriter;

public class PrintWriterExample1 {

	public static void main(String[] args) {
		
		PrintWriter writer = new PrintWriter(System.out);
		writer.write("First line of console ");
		writer.write("Second line of console");
		
		writer.flush();
		
		boolean hasError =  writer.checkError();
		System.out.println(" any error in processing - "+hasError);
		
		writer.close();
	}
}

Output

First line of console Second line of console any error in processing - false


5. Java PrintWriter Example 2 - Writing To File


Next, we will write a program to write the contents into the File rather than showing it on the console. This is very useful to store the files and for backup purposes of old contents.

Example 2

package com.javaprogramto.files.printwriter;

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

public class PrintWriterExample2 {

	public static void main(String[] args) {

		PrintWriter writer = null;
		try {
			writer = new PrintWriter(new File("src/main/resources/print_writer/test.txt"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		writer.write("First line in file ");
		writer.write("Second line in file");

		writer.flush();

		boolean hasError = writer.checkError();
		System.out.println("any error in storing in file - " + hasError);

		writer.close();
	}
}

Output

any error in storing in file - false

File output

5. Java PrintWriter Example 2 - Writing To File




6. Conclusion

In this article, we have seen how to use PrintWriter to write the objects into the console or into the file.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java PrintWriter
Java PrintWriter
A quick guide, how to write the contents into a file in java using PrintWriter class with examples.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNjrvwu_jL0PTcR2qUQSHTSijvir1ssq4AvvM5YqJ35fPj-8BX2DJZAHu5t73Hw_sysO1keVFUryHXU5coj_G7obpT7VAX3Pvpbs26DkxN0zzaryKOQK3aJ9gLB6AAHmuG8GFmeXoTUqc/w640-h378/Java+PrintWriter.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNjrvwu_jL0PTcR2qUQSHTSijvir1ssq4AvvM5YqJ35fPj-8BX2DJZAHu5t73Hw_sysO1keVFUryHXU5coj_G7obpT7VAX3Pvpbs26DkxN0zzaryKOQK3aJ9gLB6AAHmuG8GFmeXoTUqc/s72-w640-c-h378/Java+PrintWriter.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/11/java-printwriter.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/11/java-printwriter.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content