IO

Advanced Programming

SUT • Spring 2019

Contents

  • Java I/O

  • Java Files

  • Streams

  • Reader/Writer

  • Serialization

Streams

Streams

  • Data flowing into and out of a program (I/O) is called a stream

  • Streams are either

    • binary: byte-based

    • text: character-based (unicode)

  • The java.io library provides classes to handle a wide variety of I/O situations

Streams

Java I/O Classes

  • Text I/O

    • Stream of characters (Unicode format)

    • Support provided by Reader and Writer classes

  • Binary I/O

    • Stream of bytes (raw format)

    • Support provided by InputStream and OutputStream classes

Text Files

  • A text file is a common way to organize a file as a sequence of lines.

    • Each line is a sequence of characters

    • Each OS's file system has its own way to mark the ends of lines

    • java.io abstracts this in a consistent way

  • Information from text files must be parsed to identify meaningful components

    • The Scanner class helps with parsing

Binary Files

  • The term binary file is used for every other type of file organization

    • Interpreting binary files requires knowledge of how the bytes are to be grouped and interpreted

      • Text files are also binary files;

      • but the bytes have predefined meanings (character and line data)

  • Binary files provide highly efficient storage

    • Java allows entire objects to be serialized as byte sequences for this purpose

FileReader / FileWriter

  • FileReader extends

    • InputStreamReader extends

      • Reader extends Object

  • fr = new FileReader(location of a file);

    • Connects to and opens the file for character input

  • FileWriter extends

    • OutputStreamWriter extends

      • Writer extends Object

  • fw = new FileWriter(location of a file);

    • Creates and opens the file for character output

    • If the file exists, it is erased

FileReader Example

FileReader inf = new FileReader("filename");
int chCode;
while(-1 != (chCode = inf.read()) )
  System.out.println("Next char: " + (char)chCode);

inf.close();

Returned int

  • Why does Reader.read() return int, not char ?

    • Because you may read an eof

    • which is -1

  • and you'd have no way to distinguish between eof and a valid char value otherwise

Other Reader Methods

  • Reader.read() is not commonly used

  • Some other methods are (usually) better

    • int read(char[] cbuf, int off, int len)

    • int read(char[] cbuf)

    • int read(CharBuffer target)

FileWriter

FileWriter outf = new FileWriter("filename");

outf.write('A');
outf.write('\n');
outf.write("Strings too!\n");

outf.close();

Reader & Writers

  • FileReaders and FileWriters provide only very basic IO capabilities

  • The read and write methods are also overloaded to read and write an array of characters

  • FileWriter has a constructor with a boolean parameter

  • It can be used for appending the file

    • FileWriter(String fileName, boolean append)

FileInputStream/FileOutputStream

  • FileInputStream extends

    • InputStream extends Object

  • fr = new FileInputStream(location of a file);

    • Connects to and opens the file for byte-oriented input

  • FileOutputStream extends

    • OutputStream extends Object

  • fw = new FileOutputStream(location of a file);

    • Creates and opens the file for byte-oriented output

    • If the file exists, it is erased

FileInputStream

FileInputStream inf = new FileInputStream("filename");

int bCode;
while(-1 != (bCode = inf.read()))
  System.out.println("Next byte: " + (byte)bCode);
inf.close();
  • Some other InputStream methods:

    • int read(byte b[])

    • int read(byte b[], int off, int len)

FileOutputStream

FileOutputStream outf = new FileOutputStream("filename");

byte[] out = {52, 99, 13, 10};

outf.write(out);
outf.close();

InputStream/OutputStream

  • FileInputStream and FileOutputStream provides the same basic IO capabilities

  • Transfer is in bytes rather than characters.

  • There are no "lines" in these files.

  •  

  • How to append to a file

    • FileOutputStream(String name, boolean append)

Paths and Filenames

  • Microsoft chose to use the backslash character in path names

    • new FileReader("c:\textfiles\newfile.txt");

  • What is wrong with this file name?

  • In Java the backslash character in a String literal is an escape character

    • "c:{tab}extfiles{newline}ewfile.txt"

  • Either type double backslashes in String literals, or use the forward slash

    • "c:\\textfiles\\newfile.txt"

    • "c:/textfiles/newfile.txt"

RandomAccessFile

  • This class is not a reader/writer

  • nor a inputstream/outputstream

  • You can use file as binary or text file

  • Used to access desired location of file

  • For read or write

  • It has a file pointer

    • The place where you read from/write into the file

  • You can move file pointer using seek(long) method

  • It has different methods for reading and writing

Example

RandomAccessFile raf = new RandomAccessFile("c:/1.txt", "rw");

byte ch = raf.readByte();
System.out.println("first character : " + (char)ch);
ch = raf.readByte();
System.out.println("second character : " + (char)ch);
String line = raf.readLine();
System.out.println("Read a line: " + line);
raf.seek(5);
float fl = raf.readFloat();
System.out.println("Read a float from index 5: " + fl);

raf.seek(26);

raf.write('\r');
raf.write('\n');
raf.writeDouble(1.2);
raf.writeBytes("This will complete the Demo");

raf.close();

File Class

  • The java.io.File class abstracts the connection to and properties of a file or folder (directory)

  • It does not offer read/write operations

  • File f = new File("c:/data/sample.txt");

    • Sample methods: f.delete(); f.length(); f.isFile(); …

  • File d = new File("c:/");

    • This object represents a folder, not a file

File Methods

boolean canRead(); 
boolean canWrite();
boolean canExecute();
boolean exists();
boolean isFile() ;
boolean isDirectory() ;
boolean isAbsolute() ; //constructed by ”1” or “c:/test/1”
String getName();
String getPath(); // “1”
String getAbsolutePath() ; // “c:/test/1”
String getParent();
long length() ;//zero for folders
long lastModified() ;
String[] list() ;

Scanner

  • The Scanner class is not technically an I/O class

  • It is found in java.util

  • You can use a Scanner wrapped around any InputStream object to provide sophisticated token-oriented input methods

    • new Scanner(System.in);

    • new Scanner(new FileInputStream("t.txt"));

    • scanner = new Scanner(new File("sample.txt));

    • scanner.nextDouble()

    • scanner.next()

Formatter

  • Also found in java.util

  • Used to format output to text files

    • Formatter f = new Formatter("afile.txt");

    • Formatter g = new Formatter(aFileObject);

  • The format method is the most important

    • f.format("x=%d; s=%s\n", 23, "skidoo");

    • similar to printf in C++

  • The stream can be closed using…

    • g.close();

Serialization

  • Most Objects in Java are serializable

    • Can turn themselves into a stream of bytes

    • Can reconstruct themselves from a stream of bytes

  • A serialized object includes all instance variables

    • Unless marked as transient

    • Members that are Object references are also serialized

  • Serializable is an interface

  • The serialized file is a binary file

    • Not a text file

Example

public class Student implements Serializable{
	private String name;
	private String studentID;
	private double[] grades ;
	private transient double average = 17.27;


	public Student(String name, String studentID, double[] grades) {
		this.name = name;
		this.studentID = studentID;
		this.grades = grades;
	}
	public double getAverage() {
		double sum = 0;
		if(grades==null)
			return -1;
		for (double grade : grades) {
			sum+=grade;
		}
		return sum/grades.length;
	}
	//setters and getters for name, studentID and grades
}

Object Serialization

ObjectOutputStream output = new ObjectOutputStream(
    new FileOutputStream("c:/1.txt"));
    Student student = 
    new Student("Ali Alavi", "88305489", new double[]{17.2, 18.9, 20, 13});

output.writeObject(student);
output.close();

Object Deserialization

ObjectInputStream stream = new ObjectInputStream(
    new FileInputStream("c:/1.txt"));
Student student = (Student) stream.readObject();

System.out.println(student.getName());
System.out.println(student.getAverage());
stream.close();

java.net.Socket

  • This class implements client sockets

    • also called just "sockets"

  • A socket is an endpoint for communication between two machines.

  • A stream of data is communicated between two nodes

  • Very similar to local I/O operations

Writing into Socket

Socket socket = new Socket(“192.168.10.21", 8888);
OutputStream outputStream = socket.getOutputStream();
Formatter formatter = new Formatter(outputStream);
formatter.format("Salam!\n");
formatter.flush();
formatter.format("Chetori?\n");
formatter.flush();
formatter.format("exit");
formatter.flush();
socket.close();
System.out.println("finished");

Reading from a Socket

InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);

while(true){
    String next = scanner.next();
    if(next.contains("exit"))
	break;
    System.out.println("Server : " + next);
    System.out.flush();
}
socket.close();

ServerSocket

  • How to listen to other sockets?

  • What do yahoo and google do?

ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();

Binary or Text?

  • You can use a socket as a binary or text stream

The First Version of Java I/O APIs

  • java.io package

  • The File class limitations:

    • more significant functionality required (e.g. copy method)

    • defines many methods that return a Boolean value

      • In case of an error, an exception is better than a simple false.

    • Poor support for handling symbolic links

    • inefficient way of handling directories and paths

    • very limited set of file attributes

Java New IO (NIO)

  • Introduced in Java 1.4 (2002)

  • The key features of NIO were:

  • Channels and Selectors

  • Buffers

  • Charset

    • java.nio.charset

    • encoders, and decoders to map bytes and Unicode symbols

NIO.2

  • Introduced in Java 1.7 (2011)

  • Java 7 introduces the java.nio.file package

  • New interfaces and classes

    • Path, Paths, and Files

Path and Paths

  • Path  is an interface while Paths is a class

Path testFilePath = Paths.get("D:\\test\\testfile.txt");

//retrieve basic information about path
System.out.println("Printing file information: ");
System.out.println("\t file name: " + testFilePath.getFileName());
System.out.println("\t file name: " + testFilePath.getFileName());
System.out.println("\t root of path: " + testFilePath.getRoot());
System.out.println("\t parent of the target: " 
                    + testFilePath.getParent());

// print path elements 
System.out.println("Printing element of the path: ");
for(Path element: testFilePath) {
    System.out.println("\t path element: " + element);
}

Path interface

  • The toPath() method in the java.io.File class
    • returns the Path object; this method was added in Java 7
  • The toFile() method in the Path interface to get a File object
Path dirname = Paths.get("D:\\test\sub\1\");
Path resolvedPath = dirName.resolve("Test");
System.out.println(resolvedPath);

The Files Class

  • the java.nio.file package

  • Provides static methods for copy, move, delete, …

  • New methods for

    • Symbolic linked files

    • Attributes

    • ...

copy

  • it will not copy the files/directories contained in the source directory
  • you need to explicitly copy them to the destination folder
Path pathSource = Paths.get(str1);
Path pathDestination = Paths.get(str2);
Files.copy(pathSource, pathDestination);

Listening for Changes

Path path = Paths.get("..\\src");
WatchService watchService = null;

watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

Summary

  • Streams access sequences of bytes

  • Readers and Writers access sequences of characters

  • FileReader, FileWriter, FileInputStream, FileOutputStream are the 4 major file access classes

  • Scanner provides sophisticated input parsing

  • Formatter provides sophisticated output formatting

  • Most objects can be serialized for storage in a file

  • The File class encapsulates files and paths of a file system

Further Reading

  • Other java I/O classes

    • Buffered input and output

  • Decorator pattern in java.io classes

  • java.nio

  • Socket Programming

  • Object serialization applications

    • RMI

Title Text

Made with Slides.com