Java I/O (Input/Output)
Programming
• An overview of streams, console and file
operations in Java
What is I/O in Java?
• - I/O = Input / Output
• - Mechanism to read/write data
• - Packages: java.io, java.nio
Types of I/O in Java
• Console I/O: Keyboard and screen
• File I/O: File operations
• Stream I/O: Binary or text data
Streams in Java
• - A stream is a sequence of data
• - Byte Streams: For binary data
• - Character Streams: For text
Byte Streams
• FileInputStream: Read bytes
• FileOutputStream: Write bytes
• Example:
• FileOutputStream out = new
FileOutputStream("output.txt");
• out.write("Hello".getBytes());
• out.close();
Character Streams
• FileReader: Read characters
• FileWriter: Write characters
• Example:
• FileWriter fw = new FileWriter("msg.txt");
• fw.write("Welcome!");
• fw.close();
Console Input/Output
• Input:
• Scanner sc = new Scanner(System.in);
• String name = sc.nextLine();
• Output:
• System.out.println("Hello");
File Reading Example
• BufferedReader reader = new
BufferedReader(new FileReader("file.txt"));
• while ((line = reader.readLine()) != null) {
• System.out.println(line);
• }
Important I/O Classes
• Scanner, PrintWriter
• BufferedReader, BufferedWriter
• ObjectInputStream, ObjectOutputStream
Exception Handling
• Use try-catch:
• try {
• // I/O code
• } catch (IOException e) {
• System.out.println(e);
• }
Summary Table
• Read: FileReader, BufferedReader
• Write: FileWriter, PrintWriter
• Input: Scanner
• Output: System.out
• Byte: InputStream, OutputStream
Thank You