Java IO

1 minute read

  • Class with InputStream or OutputStream (in its name) -> for BinaryData
  • Class with Reader and Writer (in its name) -> for char or String data
  • A class with Buffered (in its name) -> reads or writes data in groups of bytes or characters.
    • improves performance in sequential file systems
  • A low level stream connects directly with the source of data
  • A high level stream is built on top of another stream using wrapping

COMMON STREAM OPERATIONS

Closing the stream : calling the close() in finally or using the try-with-resource syntax

Flushing the Stream : call after reasonable amount of writes

Marking the Stream : mark(int) and reset methods to move the stream back to an earlier position. markSupported() returns true only if mark() is supported

Skipping over data : skip(long) skips over a certain number of bytes

Java Input and Output

Keyboard Input

import java.util.Scanner;

Scanner in = new Scanner(System.in);

/* Input Problem: Mix of int and strings
   Extra invocation to get rid of previous \n */
int n = in.nextInt();
in.nextLine(); // To avoid INPUT Problem - consume the newline
String str = in.nextLine();

in.nextLine(); // Reads entire line
in.next(); // Reads next character up to (but not including) space

/* NO METHOD TO READ A SINGLE CHARACTER */
char a = in.nextLine().charAt(0);

File Input

import java.io.File;
import java.util.Scanner;

// Open the File
File myFile = new File("/path/to/file.txt");
Scanner in = new Scanner(myFile);

// Read from the File
String str = in.nextLine();

// OR read all lines
while (in.hasNext()) {
    System.out.println(in.nextLine());
}

// Close the File
in.close();

File Output

Writing Text to File

import java.io.PrintWriter;
import java.io.FileWriter;

final String FILENAME = "output.txt";

// Overwrite mode (surrounding with try-catch recommended)
PrintWriter output = new PrintWriter(FILENAME);
output.println("Line 1");
output.println("Line 2");
output.close();

// Append mode (to avoid erasing existing files)
PrintWriter pw = new PrintWriter(new FileWriter("output.txt", true));
pw.println("Appended line");
pw.close();

Appending Text to File

FileWriter fw = new FileWriter("Names.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("Appended content");
pw.close();

// OR in one line
PrintWriter pw = new PrintWriter(new FileWriter("Names.txt", true));

Tags:

Categories:

Updated: