0% found this document useful (0 votes)
15 views8 pages

Stram ED

Uploaded by

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

Stram ED

Uploaded by

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

CHAPTER-FOUR

Streams and File I/O


Streams and File I/O (Input/Output) are fundamental concepts in computer programming,
especially when dealing with data stored on disk or transferred over networks.
1. Streams: Streams are sequences of data elements made available over time. In programming,
streams are often used for reading from or writing to a source, such as a file or network
connection, without necessarily knowing the entire size of the data upfront. Streams enable
efficient handling of large datasets and are commonly used for processing data incrementally.
2. File I/O (Input/Output): File I/O refers to the operations of reading from and writing to files
on a storage device. It involves opening files, reading data from them, writing data to them, and
closing them when finished. File I/O operations are crucial for storing and retrieving persistent
data in programs.
In many programming languages, including Java, Python, C++, and C#, streams and file I/O are
implemented through libraries or built-in functionalities. Programmers use functions or classes
provided by these languages to work with streams and perform file I/O operations.
For example, in Java, you might use classes like FileInputStream, FileOutputStream,
BufferedReader, and BufferedWriter to read from and write to files. In Python, you would
typically use functions like open () to open files in different modes ('r' for reading, 'w' for
writing, 'a' for appending, etc.), and methods like read (), readline (), write (), and close () to
perform file I/O operations.
Understanding streams and file I/O is essential for various tasks in software development, such
as reading configuration files, processing data stored on disk, interacting with databases, and
communicating with external systems.
In Java, streams and file I/O are handled through classes and interfaces provided by the Java I/O
(java.io) and NIO (java.nio) packages. Input/output streams are fundamental for reading from
and writing to various data sources, including files, network connections, and in-memory buffers.
Here's a breakdown of key concepts and classes related to input/output streams in Java:
1. InputStream and OutputStream: These are the abstract classes at the root of all input and
output stream classes in Java. InputStream is used for reading bytes from a source, while
OutputStream is used for writing bytes to a destination.
2. Reader and Writer: These are abstract classes similar to InputStream and OutputStream but
designed for reading and writing characters instead of bytes. Readers and writers are often used
when dealing with text-based data.
3. FileInputStream and FileOutputStream: These classes are used for reading from and writing to
files as streams of bytes, respectively. They are commonly used for file I/O operations.
4. FileReader and FileWriter: These classes are used for reading from and writing to files as
streams of characters. They are built on top of FileInputStream and FileOutputStream, providing
character-based I/O.
5. BufferedInputStream and BufferedOutputStream: These classes provide buffering
functionality, which can improve the efficiency of I/O operations by reducing the number of
system calls. They wrap other input/output streams to add buffering capability.
6. BufferedReader and BufferedWriter: Similar to BufferedInputStream and
BufferedOutputStream, these classes provide buffering for character-based I/O operations. They
are commonly used for reading and writing text files efficiently.
7. DataInputStream and DataOutputStream: These classes provide methods for reading and
writing Java primitive data types (e.g., int, double, boolean) as binary data streams. They are
often used for serialization and deserialization.
8. ObjectInputStream and ObjectOutputStream: These classes provide functionality for reading
and writing Java objects as binary data streams. They are used for object serialization and
deserialization, enabling the persistence of complex data structures.
9. ByteArrayInputStream and ByteArrayOutputStream: These classes allow reading from and
writing to byte arrays as input/output streams, respectively. They are useful for in-memory I/O
operations.
10. PipedInputStream and PipedOutputStream: These classes provide a way for communication
between two threads using piped streams. Data written to a PipedOutputStream can be read from
the corresponding PipedInputStream.
These classes and concepts form the foundation for handling input/output operations in Java,
enabling developers to interact with various data sources efficiently and effectively.
Here's a simple example demonstrating how to create and read from a file using FileInputStream
in Java .
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class NewClass1 {
public static void main(String[] args) throws IOException {
//code for creating the file
File file=new File("sample.txt");
if(!file.exists()){
file.createNewFile();
}
//reading the text from the file using FileInputStream
FileInputStream fis=new FileInputStream(file);
int i=fis.read();//reads single byte from the input stream
while(!(i==-1)){
char c=(char)i;
System.out.println(c);
i=fis.read();
}
fis.close();
}
}
Here's a simple example demonstrating how to read from a file using BufferedReader in Java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class NewClass4 {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("sample.txt"))) {
String line;
while ((line = reader.readLine()) != null) {//reading line of text
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's a simple example demonstrating how to read from a file using FileOutputStream in Java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class NewClass {
public static void main(String[] args) throws IOException {
//code for creating the file
File file=new File("sample.txt");
if(!file.exists()){
file.createNewFile();
}
//witing the text into the above created file using FileOutputStream
FileOutputStream fos=new FileOutputStream(file);
String textTobeWritten="my name is bob.i learn java prgograming";
fos.write(textTobeWritten.getBytes());
fos.flush();
}
}
Here's a simple example demonstrating the usage of input and output streams in Java to copy the
contents of one file to another:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class StreamExample {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
try (FileInputStream inputStream = new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
// Buffer for efficient reading/writing
byte[] buffer = new byte[1024];
int length;
// Read from source and write to destination
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}}}
FILE MANAGEMENT
File management in Java involves creating, reading, writing, and manipulating files and
directories. Java provides several classes and methods in the java.io and java.nio packages to
handle file operations efficiently. Here's an overview of file management in Java:
1. Creating Files and Directories:File class (java.io): This class represents a file or directory path.
It can be used to create new files or directories, check file existence, and retrieve file metadata.
Files class (java.nio.file): This class provides static methods for performing file-related
operations, including creating directories, copying/moving files, and deleting files.
2. Reading from Files:FileInputStream, FileReader (java.io): These classes are used for reading
bytes and characters from files, respectively. BufferedReader (java.io): This class wraps around a
FileReader, providing buffering for efficient reading of text from a character-input stream.
3. Writing to Files:FileOutputStream, FileWriter (java.io): These classes are used for writing
bytes and characters to files, respectively. BufferedWriter (java.io): This class wraps around a
FileWriter, providing buffering for efficient writing of text to a character-output stream.
4. File Metadata: File class (java.io): It provides methods to retrieve metadata such as file size,
last modified timestamp, and file permissions. Files class (java.nio.file): It provides methods for
querying file attributes, such as checking file type, file size, and file permissions.
5. Deleting Files and Directories: File class (java.io): It provides methods to delete files and
directories using the delete () method. However, it's recommended to use Files. Delete (Path)
from the java.nio.file package for better error handling. Files class (java.nio.file): It provides
methods like delete (Path) for deleting files or directories, and walkFileTree (Path, FileVisitor)
for recursively walking a file tree and deleting files/directories.
6. File and Directory Navigation: File class (java.io): It provides methods to list files and
directories in a directory, iterate over the contents of a directory, and check if a file is a directory
or a regular file. Files class (java.nio.file): It provides methods like list(Path) and
newDirectoryStream(Path) for listing directory contents, and walk(Path, FileVisitOption...) for
traversing a directory tree.
7. File Permissions and Attributes: File class (java.io): It provides methods for querying and
setting file permissions, though it has limited support. Files class (java.nio.file): It provides more
comprehensive support for file attributes, including file permissions, ownership, and
creation/modification timestamps.
By using these classes and methods, developers can perform various file management tasks in
Java.
Here's a comprehensive example demonstrating various file management operations in Java:a,
ensuring efficient and reliable handling of file I/O operations.
import java.io.*;
import java.nio.file.*;
public class FileManagementExample {
public static void main(String[] args) {
// define paths for files and directories
String directoryPath = "example_directory";
String filePath = directoryPath + "/example_file.txt";
String copyPath = directoryPath + "/example_file_copy.txt";
try {
// create a directory
Files.createDirectory(Paths.get(directoryPath));
// Create a new file
Files.createFile(Paths.get(filePath));
// Write content to the file
String content = "Hello, World!";
Files.write(Paths.get(filePath), content.getBytes());
// Read content from the file
byte[] data = Files.readAllBytes(Paths.get(filePath));
String readContent = new String(data);
System.out.println("Read content: " + readContent);
// Copy the file
Files.copy(Paths.get(filePath),Paths.get(copyPath),
StandardCopyOption.REPLACE_EXISTING);
// List files in the directory
System.out.println("Files in directory:");
Files. List (Paths.get(directoryPath)).forEach(System.out::println);
// Delete the copied file
Files.deleteIfExists(Paths.get(copyPath));
// Delete the directory and its contents
Files.walkFileTree(Paths.get(directoryPath), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override

public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {


Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
System.out.println("Directory and its contents deleted successfully.");
} catch (IOException e) {
e.printStackTrace();
}}}
In this example:
1. We create a directory named "example_directory".
2. Inside this directory, we create a file named "example_file.txt" and write the content "Hello,
World!" to it.
3. We read the content of "example_file.txt" and print it to the console.
4. We copy "example_file.txt" to "example_file_copy.txt".
5. We list all the files in the directory.
6. We delete the copied file "example_file_copy.txt".
7. Finally, we delete the directory "example directory" and all its contents recursively.
This example demonstrates file creation, writing, reading, copying, listing, and deletion
operations in Java using the java.nio.file.Files class, along with directory creation and deletion.

You might also like