Java Files and I/O: Understanding Streams and Data Handling
Explore the java.io
package in Java, which encompasses essential classes for efficient input and output (I/O) operations. Learn about data streams, including their types and functionalities, enabling you to manage various data forms—primitives, objects, and localized characters—in your Java applications.
Java - Files and I/O
The java.io
package contains almost all the classes required for input and output (I/O) in Java. These classes handle streams, which represent an input source and an output destination. Streams in Java support various types of data such as primitives, objects, and localized characters.
Stream
A stream can be defined as a sequence of data. There are two main types of streams:
- InputStream - Used to read data from a source.
- OutputStream - Used to write data to a destination.
Byte Streams
Byte streams perform input and output of 8-bit bytes. The most commonly used classes for byte streams are FileInputStream
and FileOutputStream
. Here’s an example of copying data from one file to another using these classes:
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
}
Output
Contents of input.txt are copied to output.txt
Character Streams
While byte streams handle 8-bit bytes, character streams manage 16-bit Unicode characters. Common classes are FileReader
and FileWriter
. Here’s an example using character streams:
Example
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
}
Output
Contents of input.txt are copied to output.txt
Standard Streams
Java provides three standard streams:
- Standard Input (System.in) - Usually from the keyboard.
- Standard Output (System.out) - Usually to the display screen.
- Standard Error (System.err) - For error messages.
The following program reads characters from the console until the user types 'q':
Example
import java.io.InputStreamReader;
import java.io.IOException;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while (c != 'q');
} finally {
if (cin != null) cin.close();
}
}
}
Output
Enter characters, 'q' to quit.
1
1
a
a
q
q
File Navigation and I/O
FileInputStream
The FileInputStream
class is used to read data from a file:
Example
import java.io.FileInputStream;
import java.io.IOException;
public class FileStreamExample {
public static void main(String args[]) {
try (FileInputStream f = new FileInputStream("input.txt")) {
int i;
while ((i = f.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
This is the content of the input file.
FileOutputStream
The FileOutputStream
class is used to write data to a file:
Example
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String args[]) {
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String data = "Hello, World!";
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
"Hello, World!" is written to output.txt
Directories in Java
Creating Directories
You can use the mkdir()
or mkdirs()
methods to create directories in Java. mkdir()
creates a single directory, while mkdirs()
creates both the specified directory and all its parents.
Example
import java.io.File;
public class CreateDirectoryExample {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now
if (d.mkdirs()) {
System.out.println("Directory created successfully!");
} else {
System.out.println("Failed to create directory.");
}
}
}
Output
Directory created successfully!
Listing Directories
The list()
method of the File
class can be used to list files and directories in a directory:
Example
import java.io.File;
public class ListDirectoryExample {
public static void main(String args[]) {
File dir = new File("/tmp");
String[] files = dir.list();
if (files != null && files.length > 0) {
for (String file : files) {
System.out.println(file);
}
} else {
System.out.println("Directory is empty or does not exist.");
}
}
}
Output
bin
tmp
docs
File Permissions
Checking File Permissions
The canRead()
, canWrite()
, and canExecute()
methods can be used to check a file’s read, write, and execute permissions, respectively.
Example
import java.io.File;
public class FilePermissionExample {
public static void main(String args[]) {
File file = new File("input.txt");
System.out.println("Can read: " + file.canRead());
System.out.println("Can write: " + file.canWrite());
System.out.println("Can execute: " + file.canExecute());
}
}
Output
Can read: true
Can write: true
Can execute: false