Java File Class and I/O Stream Fundamentals
File Class
Overview and Constructors
The File class is an abstract representation of file and directory pathnames. It allows files and directories to be encapsulated as objects. It's important to note that a File object represents a pathname, not necessarily an existing file.
Constructor Methods:
| Method | Description |
|---|---|
File(String pathname) |
Creates a File instance from a pathname string |
File(String parent, String child) |
Creates a File instance from parent and child path strings |
File(File parent, String child) |
Creates a File instance from a parenet File object and child path string |
public class FileExample {
public static void main(String[] args) {
File f1 = new File("/usr/local/test.txt");
System.out.println(f1);
File f2 = new File("/usr/local", "test.txt");
System.out.println(f2);
File dir = new File("/usr/local");
File f3 = new File(dir, "test.txt");
System.out.println(f3);
}
}
Absolute vs Relative Paths
- Absolute Path: Complete path starting from the root directory
- Relative Path: Simplified path relative to the current working directory
public class PathExample {
public static void main(String[] args) {
File absPath = new File("/home/user/documents/file.txt");
File relPath = new File("data/config.txt");
File modulePath = new File("module/src/main.java");
}
}
File Creation Methods
| Method | Description |
|---|---|
boolean createNewFile() |
Creates a new empty file if it doesn't exist |
boolean mkdir() |
Creates a directory |
boolean mkdirs() |
Creates directory including any necessary parent directories |
public class FileCreation {
public static void main(String[] args) throws IOException {
File newFile = new File("/tmp/sample.txt");
System.out.println(newFile.createNewFile());
File newDir = new File("/tmp/JavaProjects");
System.out.println(newDir.mkdir());
File nestedDir = new File("/tmp/WebProject/HTML");
System.out.println(nestedDir.mkdirs());
}
}
File Deletion
public class FileDeletion {
public static void main(String[] args) throws IOException {
File targetFile = new File("project/src/temp.txt");
File targetDir = new File("project/src/temp");
System.out.println(targetFile.delete());
System.out.println(targetDir.delete());
}
}
File Inspection Methods
Checking Methods:
| Method | Description |
|---|---|
boolean isDirectory() |
Checks if this path represents a directory |
boolean isFile() |
Checks if this path represents a file |
boolean exists() |
Checks if the file/directory exists |
Retrieval Methods:
| Method | Description |
|---|---|
String getAbsolutePath() |
Returns absolute path string |
String getPath() |
Converts path to string representation |
String getName() |
Returns name of file/directory |
File[] listFiles() |
Returns array of File objects in directory |
Path Resolution Methods
Java provides three methods for path resolution:
getPath(): Returns the path string used during File object creationgetAbsolutePath(): Returns absolute path, resolving relative pathsgetCanonicalPath(): Returns unique canonical path, resolving.,.., and symbolic links
public class PathResolution {
public static void main(String[] args) throws IOException {
File file1 = new File("./config/settings.properties");
System.out.println("Path: " + file1.getPath());
System.out.println("Absolute: " + file1.getAbsolutePath());
System.out.println("Canonical: " + file1.getCanonicalPath());
}
}
Byte Streams (I/O Streams)
Overview and Classification
I/O streams handle data transfer between devices:
- Input Stream: Read operations
- Output Stream: Write operations
Streams are categorized by data type:
- Byte Streams: For binary data (images, audio, video)
- Character Streams: For text data
Writing Data with Byte Streams
Output Stream Base Classes:
OutputStream: Base class for all byte output streamsFileOutputStream: For file output operations
public class OutputStreamDemo {
public static void main(String[] args) throws IOException {
FileOutputStream output = new FileOutputStream("data/output.bin");
// Write single byte
output.write(65);
// Write byte array
byte[] data = {66, 67, 68, 69};
output.write(data);
// Write portion of array
output.write(data, 1, 2);
output.close();
}
}
Reading Data with Byte Streams
Input Stream Base Classes:
InputStream: Base class for all byte input streamsFileInputStream: For file input opertaions
public class InputStreamDemo {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream("data/input.bin");
// Read single byte
int singleByte;
while ((singleByte = input.read()) != -1) {
System.out.print((char) singleByte);
}
// Read byte array
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
input.close();
}
}
File Copy Operations
public class FileCopy {
public static void main(String[] args) throws IOException {
FileInputStream source = new FileInputStream("source.jpg");
FileOutputStream destination = new FileOutputStream("copy.jpg");
byte[] transferBuffer = new byte[4096];
int transferCount;
while ((transferCount = source.read(transferBuffer)) != -1) {
destination.write(transferBuffer, 0, transferCount);
}
destination.close();
source.close();
}
}
Buffered Streams
Buffered streams improve performance by reducing system calls:
BufferedOutputStream: Buffered output streamBufferedInputStream: Buffered input stream
public class BufferedStreamExample {
public static void main(String[] args) throws IOException {
// Buffered writing
BufferedOutputStream bufferedOut = new BufferedOutputStream(
new FileOutputStream("buffered.txt"));
bufferedOut.write("Hello World\n".getBytes());
bufferedOut.close();
// Buffered reading
BufferedInputStream bufferedIn = new BufferedInputStream(
new FileInputStream("buffered.txt"));
byte[] readBuffer = new byte[1024];
int count;
while ((count = bufferedIn.read(readBuffer)) != -1) {
System.out.print(new String(readBuffer, 0, count));
}
bufferedIn.close();
}
}
Practical Exercises
Exercise 1: Create File with Directory Check
public class CreateFileExercise {
public static void main(String[] args) throws IOException {
File directory = new File("project/data");
if (!directory.exists()) {
directory.mkdirs();
}
File targetFile = new File(directory, "data.txt");
targetFile.createNewFile();
}
}
Exercise 2: Recursive Directory Deletion
public class RecursiveDelete {
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();
}
}
Exercise 3: File Type Counter
public class FileTypeCounter {
public static void countFileTypes(File directory, Map<String, Integer> counter) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0) {
String extension = fileName.substring(dotIndex + 1);
counter.put(extension, counter.getOrDefault(extension, 0) + 1);
}
} else if (file.isDirectory()) {
countFileTypes(file, counter);
}
}
}
}
}
Exception Handling in I/O Operations
public class SafeFileOperations {
public static void main(String[] args) {
FileOutputStream stream = null;
try {
stream = new FileOutputStream("output.txt");
stream.write("Data to write".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}