0% found this document useful (0 votes)
6 views25 pages

AP m24 Week10 Fileio

Uploaded by

sanskriti gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

AP m24 Week10 Fileio

Uploaded by

sanskriti gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Advanced Programming

CSE 201
Instructor: Sambuddho

(Semester: Monsoon 2024)


Week 10 – File Streams and I/O Operations
Reading and Writing to files.
● Input stream: Used to read sequence of bytes (could be
anything ``representable’’ as a file).

● Output stream: Used to write sequence of bytes (could be


anything ``representable’’ as a file).
Reading and Writing to files.
● InputStream : abstract int read()
● [ Return values: -1 if error, or the byte read (upcasted to an int {4-bytes}). ]

● OutputStream : abstract void write(int b)


● [ Write a single byte (upcasted as an int). ]S
I/O Stream (plus Reader/Writer) Hierarchy
I/O Stream (plus Reader/Writer) Hierarchy
Reading Writing from Files

FileInputStream – Read bytes from file.


FileOutputStream – Write bytes to file
Reading Writing from Files -- PushbackInputStream
Text I/O – Reader/Writer
● char b = (char) in.read();
Text I/O – Buffered Reader
● Reader br = new BufferedReader(new BufferedInputStream(new InputStreamReader(“myfile”)));

● String next_str = br.readline(); // Read an entire line.

● char next_char = br.read(); // read single character.

● List<String> lines = Files.readAllLines(path, charset); // read multiple lines as strings for file path.

● Alternative way to read lines of a file without the List<>.

● InputStream inputStream = . . .;
● try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,
● StandardCharsets.UTF_8)))
● {
● String line;
● while ((line = in.readLine()) != null)
● {
● do something with line
● }
● }


Text I/O – File Writer
Reading and Writing Binary Data

● DataInput and DataOutput interfaces:

● readChars(), readByte(), readInt(), readShort(), readLong(), readFloat(), readDouble(), readChar(), readBoolean(),


readUTF().

● writeChars(), writeByte(), writeInt(), writeShort(), writeLong(), writeFloat(), writeDouble(), writeChar(),


writeBoolean(), writeUTF().

● Using DataInputStream and DataOutputStream:

● DataInputStream in = new DataInputStream(new FileInputStream("employee.dat"));


● DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));


Reading and Writing Binary Data
Random Access Files

● - Files are sequential access.


● - Random access files can help access at any location (seek at random
locations) – has a ``file pointer’’ much like C/C++.
● - RandomAccessFile implements both DataInput and DataOutput interfaces –
use methods like readInt()/writeInt() etc.
Zip Archive Files

● - Used for accessing compressed (.zip) files.


● - ZipInputStream class to read a .zip file.
● - ZipOutputStream class to write to a .zip file.
● - Compressed file stream stored in blocks, aka ``entires’’.
Zip Archive Files

● Writing to a ZIP file – use ZipOutputStream class.

● FileOutputStream fout = new FileOutputStream("test.zip");


● ZipOutputStream zout = new ZipOutputStream(fout);

● for all files

● {
● ZipEntry ze = new ZipEntry(filename);
● zout.putNextEntry(ze);
● zout.write(...);
● zout.closeEntry();
● }
● zout.close();
Path Interface and Files Class

● Used to work with the file system for operations like create file, delete file,
create directory etc.

● Paths – Sequence of directory names, optionally followed by a file name. The


first component is the root [e.g. / or C:\ ].

(Throws InvalidPathException if it is not a valid path)


Path Interface and Files Class

● Read path as a string from a config file.


Path resolution:

To resolve a path, e.g. to find the working


directory relative to a known path:

OR
Reading Files

Read bytes from a file into a byte array.

Read all lines are a collection of strings.

Write bytes to a file.

Reading large files:


Directories

Creating directory from path.

Creating intermediate directories.

Creating and empty file in a directory.

Creating temporary files and directories in


system-specific locations.
Copying, Moving and Deleting Files

Copy file from one location to another.

Move/rename

Copy/move with target overwrite:

Atomic move (move correctly or don’t remove sources):

Copy files from InputStream to path and from


Path to OutputStream

Delete file
Getting File Attributes

All FS attributes are encapsulated in


the BasicFileAttributes and
PosixFileAttributes
Directory Traversal/Walk
Filtering files in a directory
Directories are also files, so you can
read all the entries of a directory
and use them.

Using directory streams.


Memory Mapped I/O
- Instead of writing and reading from disk directly, map the file to a memory location and work
on it like its a flat memory.

(Caveat: In reality all files are mapped to a location of memory for faster operation, aka
BufferedReader).

Steps:
1. Get a FileChannel object of a file (like a file handle).
2. Specify the file area you want to map, using the FileChannel (1) and the mapping mode
(FileChannel.MapMode.READ_ONLY,FileChannel.MapMode.READ_WRITE,FileChannel.MapMode.P
rivate).
3. (2) provides a reference to ByteBuffer class that can be used for reading and writing like a
flat file.

Buffers can be both sequential (using the get() and put() method that advance the position) or
random-access using the actual location.
Memory Mapped I/O

Sequential access

Random access
Memory Mapped I/O

You might also like