Java I/O 02. The PrintWriter class - writing to a file

Опубликовано: 15 Май 2026
на канале: Snipcademy
1,795
5

This video is about the PrintWriter class, which is used to print to a file.

The following code may have been modified to meet Youtube's guidelines. Please go to    • Java I/O 00. Input/Output Basics Setup   to download the actual file

/**
The PrintWriter class:
To write to a file, use the PrintWriter class
Contains pretty much all the methods that System.out has.
**/

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

public class PrintWriterClass {
public static void main(String[] args) throws Exception {

File testFile = new File("printWriterTest.txt");

if (testFile.exists()) {
System.err.println("File exists");
System.exit(1);
}

PrintWriter out = new PrintWriter(testFile);

// print Strings
out.print("Hello World!");
out.println();
out.println("Hello world, it's me again.");

// print ints, doubles, booleans
out.println(13);
out.println(13.4);
out.println(true);

// flush out the buffer
out.close();

}

}