Java IO & Generics Detailed Notes
1. What is File?
A File in Java represents a physical file or directory path in the system. It does not contain file data but provides methods to manipulate files.
Features:
- Used to create, delete, and rename files
- Works with both files and directories
- Platform independent path handling
File f = new File("sample.txt");
System.out.println(f.exists());
2. How to Read File
Java provides multiple ways to read files depending on performance and requirement.
Common Classes:
- Scanner (easy but slower)
- FileReader (character based)
- BufferedReader (fast and efficient)
File f = new File("sample.txt");
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
3. Data Stream Types
A stream is a sequence of data. Java IO streams are used to read and write data.
Main Types:
- Byte Stream: Handles binary data
- Character Stream: Handles text data
4. Byte Streams
Byte streams are used for handling binary data like images, audio, and video files.
Classes:
- FileInputStream
- FileOutputStream
FileInputStream fis = new FileInputStream("a.txt");
int i;
while((i=fis.read())!=-1){
System.out.print((char)i);
}
5. Character Streams
Character streams are used for reading and writing text data. They handle Unicode characters.
Classes:
- FileReader
- FileWriter
FileReader fr = new FileReader("a.txt");
int i;
while((i=fr.read())!=-1){
System.out.print((char)i);
}
6. Further Categories of Streams
1. Buffered Streams
Improve performance by reducing IO operations.
2. Data Streams
Used to read/write primitive data types.
3. Object Streams
Used for serialization (saving objects).
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
System.out.println(br.readLine());
7. File Writing
Used to store data permanently into files.
Important Points:
- Always close the stream
- Use BufferedWriter for better performance
FileWriter fw = new FileWriter("a.txt");
fw.write("Hello Java");
fw.close();
8. Random Access File
Allows reading and writing at any position in a file.
Advantages:
- Direct access to data
- Efficient for large files
RandomAccessFile raf = new RandomAccessFile("a.txt","rw");
raf.writeUTF("Hello");
raf.seek(0);
System.out.println(raf.readUTF());
9. Purpose of Generics
Generics enable type-safe and reusable code.
Advantages:
- Compile-time error checking
- No need for type casting
- Improves code readability
class Box<T>{
T value;
}
10. Generic Class
A class that works with different data types using type parameters.
class Data<T>{
T data;
Data(T d){data=d;}
}
11. Generic Method
A method that can operate on different types.
public static <T> void print(T[] arr){
for(T i:arr) System.out.println(i);
}
No comments:
Post a Comment