Working with Files

In Java, the File class from the java.io package is used to abstract and handle files and directories.

File file = new File("./data.txt");
 
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("Does the file exist? " + file.exists());
  • new File("data.txt"): Creates a File object representing the file "data.txt".
  • getAbsolutePath(): Returns the full path to the file.
  • exists(): Checks whether the file or directory actually exists in the filesystem.

Java I/O Overview

  • Java handles input/output (I/O) through streams to process data efficiently.
  • The main API for I/O operations:
    • java.io → traditional, blocking I/O
    • java.nio → newer, non-blocking I/O (NIO = New I/O)

I/O Stream

  • Java handles input and output (I/O) through the concept of streams, which allow you to read/write data sequentially (like a pipe).
  • Different from Stream in Java

Kinds of I/O Streams

TypeDescriptionExamples
InputReads data into the programInputStream, Reader
OutputWrites data out of the programOutputStream, Writer
Byte-basedFor binary data (e.g., images, raw files)InputStream, OutputStream
Character-basedFor text data (UTF-16 characters)Reader, Writer

Classification: Node vs Filter Streams

Node Streams (기본 스트림)

Directly connected to a data source or destination (file, memory, network)

TypeInput StreamOutput Stream
Byte-basedInputStreamOutputStream
Char-basedReaderWriter
  • When reading data by byte: InputStream
  • When writing data by byte: OutputStream
  • When reading data by character: Reader
  • When writing data by character: Writer

Filter Streams (보조 스트림)

Wrap around node streams to add features like buffering, formatting, etc.

PurposeInput StreamOutput Stream
BufferingBufferedReaderBufferedWriter
Character conversionInputStreamReaderOutputStreamWriter
Reading/writing primitivesDataInputStreamDataOutputStream
Object serialization (object streams)ObjectInputStreamObjectOutputStream
  • Most BufferedXXX classes in Java I/O wrap around a non-buffered “node stream” (like FileWriter, InputStream, etc.) — they don’t work alone.
BufferedWriter writer = new BufferedWriter(new FileWriter("scores.txt"));
writer.write("hello");
writer.close();
  • FileWriter opens a real connection to the file.
  • BufferedWriter wraps it to buffer character output, reducing slow disk writes.

Example: ObjectOutputStream

FileOutputStream fos = new FileOutputStream("channelName.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(channel); // writes the object in binary format
  • object streams serialize Java objects into a special binary format that Java can deserialize later
  • It’s not the same as writing text or raw bytes—you’re preserving object structure, including fields and types

Examples (Byte-based)

Using FileInputStream - reading data from the files

import java.io.FileInputStream;
 
public class FileInputStreamExample {
    public static void main(String[] args) {
        try {
            FileInputStream fileInput = new FileInputStream("java.txt");
            int i;
            while ((i = fileInput.read()) != -1) {
                System.out.print((char) i);
            }
            fileInput.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Using BufferedInputStream

import java.io.FileInputStream;
import java.io.BufferedInputStream;
 
public class FileInputStreamBuffered {
    public static void main(String[] args) {
        try {
            FileInputStream fileInput = new FileInputStream("java.txt");
            BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
            int i;
            while ((i = bufferedInput.read()) != -1) {
                System.out.print((char) i);
            }
            bufferedInput.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
  • BufferedInputStream uses buffer internally

Using FileOutputStream - create a file (if it doesn’t exist) and write data into it

import java.io.FileOutputStream;
 
public class FileOutputStreamExample {
    public static void main(String[] args) {
        try {
            FileOutputStream fileOutput = new FileOutputStream("java.txt");
            String word = "ja";
            byte[] b = word.getBytes();
            fileOutput.write(b);
            fileOutput.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
 

Examples (Char-based)

Saving List data into txt

  • use flush() and close()
    • flush() - puts data in buffer to destination
List<String> names = List.of("Alice", "Bob", "Charlie");
 
BufferedWriter writer = null;
 
try {
    writer = new BufferedWriter(new FileWriter("names.txt"));
    
    for (String name : names) {
        writer.write(name);
        writer.newLine();
    }
    
    writer.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • You can use a set too (Set.of instead of List.of), but the order is not guaranteed

Saving Map data into txt file

Map<String, Integer> scoreMap = Map.of("Tom", 90, "Jane", 85, "Paul", 95);
 
BufferedWriter writer = null;
 
try {
    writer = new BufferedWriter(new FileWriter("scores.txt"));
    
    for (Map.Entry<String, Integer> entry : scoreMap.entrySet()) {
        writer.write(entry.getKey() + ":" + entry.getValue());
        writer.newLine();
    }
    
    writer.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Saving data from txt file into List

List<String> names = new ArrayList<>();
 
BufferedReader reader = null;
 
try {
    reader = new BufferedReader(new FileReader("names.txt"));
    String line;
    
    while ((line = reader.readLine()) != null) {
        names.add(line);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Saving data from txt file into Map

Map<String, Integer> scoreMap = new HashMap<>();
 
BufferedReader reader = null;
 
try {
    reader = new BufferedReader(new FileReader("scores.txt"));
    String line;
    
    while ((line = reader.readLine()) != null) {
	    // this is the part that changed!
        String[] parts = line.split(":");
        if (parts.length == 2) {
            scoreMap.put(parts[0], Integer.parseInt(parts[1]));
        }
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}