IO

From Suhrid.net Wiki
Jump to navigationJump to search

Basic Classes

  • The File class is an abstract representation of files and directory pathnames. It works at a higher level, cant be used to read/write data.
  • FileReader - read character levels - variety of read() methods. Usually wrapped in a BufferedReader.
  • BufferedReader - Reads large chunks of files and keeps it in the buffer. Subsequent requests are got from the buffer thus minimizing the number of times time intensive file IO is performed.

Similarly:

  • FileWriter - write to character files.
  • BufferedWriter - Keeps data in buffer and writes large chunks of buffer to file at once, minimizing file IO.
  • PrintWriter - Has a lot of convenience methods and constructors (takes a File or String etc). Methods like format(), printf() and append() make PrintWriters powerful.
  • NOTE: Many of the IO Based methods throw checked IOException or its subclass - watch out.

Remember:

  • For Characters - Reader and Writer classes are used.
  • For Bytes - Stream classes are used.

Writer Classes

FileWriter

  • Writes characters to a File.
  • Uses FileOutputStream for underlying byte level IO.
  • FileWriter constructor takes a File/Filename, and a boolean flag to indicate whether the file should be opened in append mode.
  • By default append is false, which means the filewriter will overwrite existing file contents. If append is true, write() methods will append characters to the existing content.
  • Has overloaded write() methods, that take char[], String etc and indexes (to write portion of String)
    • e.g. write(char[] cbuf), write(char[], int off, int len), write(String s, int off, int len)
  • Has overloaded newer append() methods (behaves exactly like write) that take CharSequence.
    • append(CharSeq), append(CharSequence cs, int start, int end)
    • All the constructors and methods throw a checked IOException

BufferedWriter

  • Typically will wrap an underlying stream for better performance.
  • Same set of write() and append() methods.
  • NOTE: Unless FileWriter opens a file in append mode, then the Writers will overrwrite the contents of the file.
public class IPOP1 {

	public static void main(String[] args) {
		
		File f = new File("/tmp/loremipsum.out");
		
		try {
			
			StringBuilder sb = new StringBuilder("Lorem ipsum dolor sit amet, consectetur adipiscing elit");
			
			BufferedWriter bfw = new BufferedWriter(new FileWriter(f));
			
			bfw.write(sb.toString());

                        bfw.write(sb.toString(), 0, 11); //Will write Lore ipsum only
			
			bfw.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

PrintWriter

  • PrintWriter offers convenience methods and constructors.
  • PrintWriter flushes the buffer with every invocation of println() or format().
  • PrintWriter can write directly to a File, without needing to wrap a FileWriter.
  • It has the following overloaded methods:
    • NONE of the PrintWriter()'s methods throw IOException !
    • write() - inherited from java.io.Writer
    • append() - from java.io.Appendable
    • format() - print formatted strings
    • print() - primitives to object
    • printf() - same as format()
    • println() - primitives and objects, Convenience method.

Reader Classes

FileReader

  • Used to read character files.
  • Uses FileInputStream for underlying byte level IO.
  • Constructors take a File/FileName and throw a FileNotFoundException if file not found or is a directory or cannot be opened for some reason.
  • Has a basic read(char[] cbuf) method.
  • Not convenient since char[] array size has to be big enough.

BufferedReader

  • Buffers input for performance
  • Overloaded constructors take a java.io.Reader and an optional buffer size.
  • All the read() methods throw an IOException.
  • Has the convenient readLine() method.
import java.io.*;

public class IPOP2 {

	public static void main(String[] args) {
		
		File li = new File("/tmp/loremipsum.out");
		
		try {
		
			FileReader fr = new FileReader(li);
			
			BufferedReader br = new BufferedReader(fr);
			
			String str;
			
			while((str = br.readLine()) != null) {
				System.out.println(str);
			}
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
	}
}

File Class

  • A File object can represent a file or a directory.
  • File f = new File("a.txt") just creates an object representing the file, doesnt create the file on the disk.
  • createNewFile() - will attempt to create a file. Returns true/false depending on the success status.
  • Creating a reader/writer/stream will also automatically create a file if it doesnt exist.
  • mkdir() - will create a directory.
  • list() - returns a String[] of directory contents if the File represents a dir, else it will return null.
  • canRead(), canWrite(), canExecute() - can be used to check for R/W/X permissions.
  • Deleting is done for both files and directories using the delete() method.
  • Directory which is not empty CANNOT be deleted. delete() will just return false.
  • renameTo() works for both files and directories. Non-empty directory can be renamed too.
  • Paths:
public static void main(String[] args) {
		try {
			//Current path : /home/suhridk/eclipsews/OCPJP/bin
			File f = new File("../somefile.txt");
			System.out.println(f.getPath());          // prints: ../somefile.txt
			System.out.println(f.getAbsolutePath());  // Path from the begining : prints: /home/suhridk/eclipsews/OCPJP/../somefile.txt
			System.out.println(f.getCanonicalPath()); // All relative references resolved: prints: /home/suhridk/eclipsews/somefile.txt
		} catch (Exception e) {
			e.printStackTrace();
		}
}

Console

  • A console is a unique character based device associated with a JVM. Represented by java.io.Console.
  • Whether a JVM has a console or not depends on the platform and the manner in which a JVM is invoked. for e.g. an appserver will not have a console.
  • For a JVM started on the cmd line, the console corresponds to the keyboard and the display monitor.
  • Console console = System.console();
  • Console class provide overloaded readLine() methods to read a String from the console, one takes a format string like printf() to print a prompt.
  • Also similarly provides overloaded readPassword() methods which dont echo the password on the console and return a char[] array.
import java.io.*;
import java.util.Arrays;
import java.util.Date;

public class ConsTest2 {

	public static void main(String[] args) {
		
		Console c = System.console();
		if(c!=null) {
			System.out.println("Got the console");
			String name = c.readLine("Hello, the current time is %s, enter your name : ", new Date());
			System.out.println("Welcome " + name);
		    char[] password = c.readPassword("Please enter your password to continue ");
		    if(Arrays.equals(password, new char[] {'K','a','b','u','k','i'})) {
		    	System.out.println("Correct password ! Greetings, overlord !");
		    } else {
		    	System.out.println("Incorrect password, you will be reported !");
		    }
		}
	}
}