Java File Handling and Stream Processing Guide

Reading Console Input ------- Java's console is handled through System.in. To create a character stream bound to the console, you can wrap System.in in a BufferedReader object. BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); After creating the BufferedReader object, you can use the read() method to read a single character from the console or the readLine() method to read a string. System.in reads byte streams, so InputStreamReader is needed to convert bytes to characters. Reading Multi-character Input from Console ----------- To read a character from a BufferedReader object, use the read() method int read() throws IOException consoleReader.read() returns an int value that needs to be explicitly cast to char Reading Strings from Console --------- Reading strings from standard input requires using the BufferedReader's readLine() method String readLine() throws IOException // Using BufferedReader to read characters from console import java.io.*; public class ConsoleInputReader { public static void main(String[] args) throws IOException { // Create BufferedReader using System.in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inputText; System.out.println("Enter lines of text."); System.out.println("Enter 'quit' to finish."); do { inputText = reader.readLine(); System.out.println(inputText); } while (!inputText.equals("quit")); } } FileInputStream --------------- You can create an input stream object using a string filename InputStream fileStream = new FileInputStream("C:\JAVA\Greetings"); Alternatively, you can use a File object to create an input stream for reading files File fileObj = new File("C:\JAVA\greetings"); InputStream inputStream = new FileInputStream(fileObj); Common methods: FileOutputStream ---------------- Create an output stream object using a string filename: OutputStream outputStream = new FileOutputStream("c:\java\greetings"); You can also use a File object to create an output stream for writing files File fileObj = new File("C:\JAVA\greetings"); OutputStream fileOutputStream = new FileOutputStream(fileObj); import java.io.*; public class BinaryFileOperations { public static void main(String[] args) { try { byte dataToWrite[] = { 10, 20, 3, 40, 5 }; OutputStream output = new FileOutputStream("sample.txt"); for (int index = 0; index < dataToWrite.length; index++) { output.write(dataToWrite[index]); // writes the bytes } output.close(); InputStream input = new FileInputStream("sample.txt"); int dataSize = input.available(); for (int counter = 0; counter < dataSize; counter++) { System.out.print((char) input.read() + " "); } input.close(); } catch (IOException exception) { System.out.print("Error occurred"); } } } The above code may produce garbled output since it's writing binary data // File name :CharacterFileExample.java import java.io.*; public class CharacterFileExample { public static void main(String[] args) throws IOException { File file = new File("output.txt"); FileOutputStream fileOutput = new FileOutputStream(file); // FileOutputStream object is created, file will be created if it doesn't exist OutputStreamWriter writer = new OutputStreamWriter(fileOutput, "UTF-8"); // OutputStreamWriter object is created, encoding can be specified, default is OS encoding (GBK on Windows) writer.append("Chinese text input"); // Write to buffer writer.append("\r\n"); // New line writer.append("English text"); // Flush buffer to file, if there's no more content to write, closing will also write writer.close(); // Close writer, which also writes buffer content to file fileOutput.close(); // Close output stream, release system resources FileInputStream fileInput = new FileInputStream(file); // Create FileInputStream object InputStreamReader reader = new InputStreamReader(fileInput, "UTF-8"); // Create InputStreamReader object with same encoding as writing StringBuilder content = new StringBuilder(); while (reader.ready()) { content.append((char) reader.read()); // Convert to char and append to StringBuilder } System.out.println(content.toString()); reader.close(); // Close reader stream fileInput.close(); // Close input stream, release system resources } } Java Directories -------- ### Creating Directories - mkdir() creates a single directory. Returns true on success, false on failure - mkdirs() creates a directory and all necessary parent directories import java.io.File; public class DirectoryCreator { public static void main(String[] args) { String path = "/home/user/java/bin"; File directory = new File(path); // Create directory directory.mkdirs(); } } ### Reading Directories import java.io.File; public class DirectoryLister { public static void main(String args[]) { String dirPath = "/home"; File dir = new File(dirPath); if (dir.isDirectory()) { System.out.println("Contents of " + dirPath); String entries[] = dir.list(); for (int i = 0; i < entries.length; i++) { File entry = new File(dirPath + "/" + entries[i]); if (entry.isDirectory()) { System.out.println(entries[i] + " is a directory"); } else { System.out.println(entries[i] + " is a file"); } } } else { System.out.println(dirPath + " is not a directory"); } } } #### Deleting Directories and Files When deleting a directory, you must ensure it contains no other files, otherwise the deletion will fail import java.io.File; public class DirectoryCleaner { public static void main(String[] args) { // Change to your test directory File targetFolder = new File("/home/java/"); deleteFolder(targetFolder); } // Delete files and directories public static void deleteFolder(File folder) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteFolder(file); } else { file.delete(); } } } folder.delete(); } }

Tags: java IO Streams File Handling Console Input

Posted on Thu, 07 May 2026 01:55:22 +0000 by jug