June 2024
Basic I/O in Java
JUNE, 2024
CONTENT
I/O Streams
Scanning and Formatting
File I/O (NIO.2)
Legacy File I/O
JUNE, 2024
I/O Streams
Definition:
• Mechanism to read and write data
Types:
• Byte Streams
• Character Streams
JUNE, 2024
Byte Streams
Description:
• Handles I/O of raw binary data
Classes:
• InputStream
• OutputStream
Example:
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]();
[Link]();
JUNE, 2024
Character Streams
Description:
• Handles I/O of character data
Classes:
• Reader
• Writer
Example:
FileReader in = new FileReader("[Link]");
FileWriter out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]();
[Link]();
JUNE, 2024
Buffered Streams
Description:
• Enhances performance by buffering I/O operations
Classes:
• BufferedReader
• BufferedWriter
Example:
BufferedReader in = new BufferedReader(new FileReader("[Link]"));
BufferedWriter out = new BufferedWriter(new FileWriter("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
[Link]();
[Link]();
JUNE, 2024
Scanning
Description:
• Parses primitive types and strings using regular
expressions
Classes:
• Scanner
Example:
Scanner scanner = new Scanner(new File("[Link]"));
while ([Link]()) {
[Link]([Link]());
}
[Link]();
JUNE, 2024
Formatting
Description:
• Formats data into human-readable form
Classes:
• Formatter
Example:
Formatter formatter = new Formatter();
[Link]("PI = %.2f", [Link]);
[Link](formatter);
[Link]();
JUNE, 2024
I/O from the Command Line
Description:
• Reading input and writing output using standard I/O
streams
Classes:
• Formatter
Example:
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
JUNE, 2024
Data Streams
Description:
• Reads and writes primitive data types
Classes:
• DataInputStream
• DataOutputStream
Example:
DataOutputStream out = new DataOutputStream(new
FileOutputStream("[Link]"));
[Link](123);
[Link](456.78);
[Link]();
DataInputStream in = new DataInputStream(new FileInputStream("[Link]"));
int intValue = [Link]();
double doubleValue = [Link]();
[Link]();
JUNE, 2024
Object Streams
Description:
• Reads and writes objects
Classes:
• ObjectInputStream
• ObjectOutputStream
Example:
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](new Date());
[Link]();
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("[Link]"));
Date date = (Date) [Link]();
[Link]();
JUNE, 2024
File I/O (Featuring NIO.2)
• Introduction to NIO.2
• Key Features:
⚬ Path Class
⚬ File Operations
⚬ Metadata Management
⚬ Directory and File Tree
Operations
JUNE, 2024
What Is a Path?
Description:
• Represents a location in the file
system
Class:
• [Link]
Example:
Path path = [Link]("[Link]");
[Link]([Link]());
JUNE, 2024
The Path Class
The Path Class:
• Represents a location in the file system
Example:
Path path = [Link]("[Link]");
[Link]("Root: " + [Link]());
[Link]("Parent: " + [Link]());
[Link]("Name Count: " +
[Link]());
JUNE, 2024
Path Operations
Common Operations:
• resolve()
• relativize()
• normalize()
Example:
Path path1 = [Link]("dir1/dir2"); // path1 represents the directory
"dir1/dir2"
Path path2 = [Link]("dir3/[Link]"); // path2 represents the file
"dir3/[Link]"
Path resolvedPath = [Link](path2); // Resolving path2 against
path1
[Link](resolvedPath); // Output the resolved path:
dir1/dir2/dir3/[Link]
JUNE, 2024
File Operations
Common Operations:
• Checking a File or Directory
boolean fileExists = new File("path/to/[Link]").exists();
• Deleting a File or Directory
boolean deleted = new File("path/to/[Link]").delete();
• Copying a File or Directory
[Link]([Link]("sourcePath/[Link]"), [Link]("destinationPath/[Link]"),
StandardCopyOption.REPLACE_EXISTING);
• Moving a File or Directory
[Link]([Link]("sourcePath/[Link]"),
[Link]("destinationPath/[Link]"),StandardCopyOption.REPLACE_EXISTING);
JUNE, 2024
Checking a File or Directory
Methods:
• [Link]()
• [Link]()
Example:
Path path = [Link]("[Link]");
if ([Link](path)) {
[Link](path + " exists");
}
JUNE, 2024
Deleting a File or Directory
Methods:
• [Link]()
Example:
Path path = [Link]("[Link]");
[Link](path);
JUNE, 2024
Copying a File or Directory
Methods:
• [Link]()
Example:
Path source = [Link]("[Link]");
Path target = [Link]("[Link]");
[Link](source, target);
JUNE, 2024
Moving a File or Directory
Methods:
• [Link]()
Example:
Path source = [Link]("[Link]");
Path target = [Link]("[Link]");
[Link](source, target);
JUNE, 2024
Managing Metadata
Description:
• Reading and setting file attributes
Methods:
• [Link]()
• [Link]()
Example:
Path path = [Link]("[Link]");
Object size = [Link](path, "size");
[Link]("File size: " + size);
JUNE, 2024
Managing Metadata
Methods Comment
Returns the size of the specified file in bytes.
size(Path)
Returns true if the specified Path locates a file that is a directory.
isDirectory(Path, LinkOption)
Returns true if the specified Path locates a file that is a regular
isRegularFile(Path, LinkOption...) file.
Returns true if the specified Path locates a file that is a symbolic
isSymbolicLink(Path) link.
Returns true if the specified Path locates a file that is considered
isHidden(Path) hidden by the file system.
getLastModifiedTime(Path, LinkOption...) Returns or sets the specified file's last modified time.
setLastModifiedTime(Path, FileTime)
getOwner(Path, LinkOption...) Returns or sets the owner of the file.
setOwner(Path, UserPrincipal)
JUNE, 2024
Reading, Writing, and Creating
Methods: Files
• [Link]()
• [Link]()
• [Link]()
Example:
Path path = [Link]("[Link]");
[Link](path, "Hello, World!".getBytes());
byte[] bytes = [Link](path);
[Link](new String(bytes));
JUNE, 2024
Random Access Files
Description:
• Reads and writes to any position in a file
Class:
• RandomAccessFile
Example:
RandomAccessFile file = new RandomAccessFile("[Link]",
"rw");
[Link](100);
[Link]("Hello, World!");
[Link]();
JUNE, 2024
Creating and Reading Directories
Methods:
• [Link]()
• [Link]()
Example:
Path dir = [Link]("newdir");
[Link](dir);
DirectoryStream<Path> stream =
[Link](dir);
for (Path path : stream) {
[Link]([Link]());
}
JUNE, 2024
Links, Symbolic or Otherwise
Description:
• Creating and handling symbolic links
Methods:
• [Link]()
• [Link]()
Example:
Path link = [Link]("link");
Path target = [Link]("[Link]");
[Link](link, target);
JUNE, 2024
Walking the File Tree
Description:
• Recursively visit files and directories
Class:
• FileVisitor
Example:
Path start = [Link]("startdir");
[Link](start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
[Link](file);
return [Link];
}
});
JUNE, 2024
Finding Files
Description:
• Locating files using search criteria
Methods:
• [Link]()
Example:
Path start = [Link]("startdir");
try (Stream<Path> stream = [Link](start, Integer.MAX_VALUE,
(path, attr) -> [Link](path).endsWith(".txt"))) {
[Link]([Link]::println);
}
JUNE, 2024
Watching a Directory for Changes
Description:
• Monitor changes in a directory
Classes:
• WatchService
• WatchKey
• WatchEvent
Example:
Path path = [Link]("watchdir");
WatchService watchService = [Link]().newWatchService();
[Link](watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = [Link]()) != null) {
for (WatchEvent<?> event : [Link]()) {
[Link]("Event kind:" + [Link]() + ". File affected: " + [Link]() +
".");
}
[Link]();
}
JUNE, 2024
Other Useful Methods
Methods:
• [Link]()
• [Link]()
• [Link]()
Example:
Path path = [Link]("[Link]");
long size = [Link](path);
boolean isReadable = [Link](path);
boolean isWritable = [Link](path);
[Link]("Size: " + size + ", Readable: " + isReadable +
", Writable: " + isWritable);
JUNE, 2024
Legacy File I/O Code
Introduction to Legacy I/O Classes:
• File
• FileInputStream
• FileOutputStream
• RandomAccessFile
Example: File Class
File file = new File("[Link]");
if ([Link]()) {
[Link]("File exists: " + [Link]());
} else {
[Link]();
[Link]("File created: " + [Link]());
}
JUNE, 2024
Legacy File I/O Code - Reading and
Writing
Example: Reading from a File using
FileInputStream
FileInputStream fis = new FileInputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link]((char) c);
}
Example: Writing to a File using
[Link]();
FileOutputStream
FileOutputStream fos = new FileOutputStream("[Link]");
String data = "Hello, World!";
[Link]([Link]());
[Link]();
JUNE, 2024
Legacy File I/O Code - Random Access
Example: Random Access File
RandomAccessFile raf = new RandomAccessFile("[Link]",
"rw");
[Link]("Hello, World!");
[Link](0);
[Link]([Link]());
[Link]();
June 2024
thank you