Skip to main content
Advertisement

Standard I/O and the File Class

1. Standard I/O

Java provides three pre-configured (built-in) standard streams as static final variables inside the System class. They are predominantly used for receiving input from the user via the console window or printing text onto the console.

  • System.in: A byte-based input stream (InputStream) designed to receive data from the console.
  • System.out: A byte-based output stream (PrintStream) utilized for printing data to the console.
  • System.err: A stream specifically reserved for outputting error messages (typically rendered in red text by most IDE consoles).
import java.io.IOException;

public class StandardIOEx {
public static void main(String[] args) {
System.out.println("Type characters (terminate with ctrl+z or ctrl+d): ");
System.err.println("This is a message printed via the error stream.");

try {
int input;
while ((input = System.in.read()) != -1) {
System.out.print((char) input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. The File Class

The java.io.File class functions not as an I/O stream, but primarily as a utility class that handles the control and information retrieving of Files or Directories themselves. It is commonly used when you need to query file metadata (file size, write permissions) or when programmatically creating or deleting folders and files. Although utilizing improved API alternatives (java.nio.file.Files and Path) introduced in Java 7 is often recommended, the standard File class remains heavily utilized today.

import java.io.File;
import java.io.IOException;

public class FileExample {
public static void main(String[] args) throws IOException {
File file = new File("C:\\example", "new_file.txt");
File dir = new File("C:\\example");

// Create the directory if it does not exist
if (!dir.exists()) {
dir.mkdirs();
}

// Create a new blank file if it does not exist
if (!file.exists()) {
boolean isCreated = file.createNewFile();
System.out.println("File Creation Status: " + isCreated);
}

System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
}
}

File objects are generally instantiated and then actively passed into the constructor of an I/O stream (e.g., FileInputStream), bridging standard file metadata access with dynamic data stream handling.

Advertisement