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 aFile
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/Ojava.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
Type | Description | Examples |
---|---|---|
Input | Reads data into the program | InputStream , Reader |
Output | Writes data out of the program | OutputStream , Writer |
Byte-based | For binary data (e.g., images, raw files) | InputStream , OutputStream |
Character-based | For 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)
Type | Input Stream | Output Stream |
---|---|---|
Byte-based | InputStream | OutputStream |
Char-based | Reader | Writer |
- 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.
Purpose | Input Stream | Output Stream |
---|---|---|
Buffering | BufferedReader | BufferedWriter |
Character conversion | InputStreamReader | OutputStreamWriter |
Reading/writing primitives | DataInputStream | DataOutputStream |
Object serialization (object streams) | ObjectInputStream | ObjectOutputStream |
- Most
BufferedXXX
classes in Java I/O wrap around a non-buffered “node stream” (likeFileWriter
,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()
andclose()
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 ofList.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();
}
}
}