Reading Console Input
In Java, console input is handled by System.in. To read character data from the console, you typically wrap System.in with an InputStreamReader to convert the byte stream into a character stream, and then wrap that with a BufferedReader for efficient line-based reading.
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
Once the BufferedReader object is created, you can use read() to read a single character or readLine() to read an entire line of text. Since System.in provides a byte stream, InputStreamReader is necessary to transform it into a character stream.
Reading a Single Character
To read a single character from the BufferedReader object, use the read() method.
int read() throws IOException
The consoleReader.read() method returns an integer, which you must explicitly cast to a char.
Reading a String
To read a string from standard input, use the readLine() method of BufferedReader.
String readLine() throws IOException
// Example: Using BufferedReader to read lines from the console
import java.io.*;
public class ConsoleInputExample {
public static void main(String[] args) throws IOException {
// Create a BufferedReader to read from System.in
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine;
System.out.println("Enter lines of text.");
System.out.println("Enter 'quit' to stop.");
do {
inputLine = consoleReader.readLine();
System.out.println("You entered: " + inputLine);
} while (!inputLine.equalsIgnoreCase("quit"));
}
}
File Input and Output
FileInputStream
You can create a FileInputStream by specifying a file path as a string.
InputStream fileInput = new FileInputStream("C:/data/input.txt");
Alternatively, you can create an input stream by passing a File object representing the file.
File fileObj = new File("C:/data/input.txt");
InputStream fileInput = new FileInputStream(fileObj);
FileOutputStream
To create an output stream for writing to a file, you can use a string for the file name.
OutputStream fileOutput = new FileOutputStream("C:/data/output.txt");
You can also create an output stream using a File object.
File fileObj = new File("C:/data/output.txt");
OutputStream fileOutput = new FileOutputStream(fileObj);
// Example: Writing and reading binary data to a file
import java.io.*;
public class BinaryFileExample {
public static void main(String[] args) {
try {
// Data to be written to the file
byte[] byteData = { 65, 66, 67, 68, 69 };
// Create an output stream to write to the file
OutputStream outputStream = new FileOutputStream("binary_data.bin");
for (int i = 0; i < byteData.length; i++) {
outputStream.write(byteData[i]); // Write each byte
}
outputStream.close();
// Create an input stream to read from the file
InputStream inputStream = new FileInputStream("binary_data.bin");
int availableBytes = inputStream.available();
System.out.print("File content: ");
for (int i = 0; i < availableBytes; i++) {
System.out.print((char) inputStream.read() + " ");
}
inputStream.close();
} catch (IOException e) {
System.out.println("An I/O error occurred.");
}
}
}
The above code writes binary data, which can lead to encoding issues when reading text. To handle text files correctly, especially with non-ASCII characters, it's better to use character streams with a specified encoding.
// Example: Writing and reading text data with UTF-8 encoding
import java.io.*;
public class TextFileExample {
public static void main(String[] args) throws IOException {
File file = new File("text_data.txt");
// Create FileOutputStream, file is created if it doesn't exist
FileOutputStream fileOutputStream = new FileOutputStream(file);
// Create OutputStreamWriter with UTF-8 encoding
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, "UTF-8");
// Write text to the buffer
writer.append("This is some text.");
writer.append("\n"); // New line
writer.append("This includes non-ASCII characters: é, ü, ¥.");
// Close the writer, which flushes the buffer to the file
writer.close();
// Close the output stream
fileOutputStream.close();
// Create FileInputStream to read the file
FileInputStream fileInputStream = new FileInputStream(file);
// Create InputStreamReader with the same UTF-8 encoding
InputStreamReader reader = new InputStreamReader(fileInputStream, "UTF-8");
StringBuilder contentBuilder = new StringBuilder();
while (reader.ready()) {
contentBuilder.append((char) reader.read());
}
System.out.println("File content:\n" + contentBuilder.toString());
// Close the reader
reader.close();
// Close the input stream
fileInputStream.close();
}
}
Working with Directories
Creating Directories
mkdir(): Creates a single directory. Returnstrueon success,falseif the directory already exists or cannot be created.mkdirs(): Creates a directory and all necessary parent directories.
import java.io.File;
public class DirectoryCreationExample {
public static void main(String[] args) {
String directoryPath = "/tmp/user/java/bin";
File directory = new File(directoryPath);
// Create the directory and all parent directories if they don't exist
boolean created = directory.mkdirs();
if (created) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Directory already exists or could not be created.");
}
}
}
Listing Directory Contents
import java.io.File;
public class DirectoryListingExample {
public static void main(String args[]) {
String directoryPath = "/tmp";
File directory = new File(directoryPath);
if (directory.isDirectory()) {
System.out.println("Contents of directory: " + directoryPath);
String[] entries = directory.list();
for (String entry : entries) {
File currentFile = new File(directoryPath + "/" + entry);
if (currentFile.isDirectory()) {
System.out.println(entry + " is a directory");
} else {
System.out.println(entry + " is a file");
}
}
} else {
System.out.println(directoryPath + " is not a directory");
}
}
}
Deleting Directories and Files
When deleting a directory, it must be empty. To delete a directory and all its contents, you must recursively delete all files and subdirectories within it first.
import java.io.File;
public class DirectoryDeletionExample {
public static void main(String[] args) {
// Replace with your target directory path
File targetDirectory = new File("/tmp/java/");
deleteDirectory(targetDirectory);
}
// Recursively deletes a directory and all its contents
public static void deleteDirectory(File directory) {
File[] contents = directory.listFiles();
if (contents != null) {
for (File item : contents) {
if (item.isDirectory()) {
deleteDirectory(item);
} else {
item.delete();
}
}
}
directory.delete();
}
}