Byte Streams

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we’ll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed. Consider the following example for reading a text file.

import java.io.*;

public class FileReadExample {
	public static void main(String[] args) throws IOException {
		FileInputStream in = null;
		int c;
		in = new FileInputStream("abc.txt"); // opening a file
		while ((c = in.read()) != -1) {
			System.out.print((char)c); // typecast ASCII value to character
		}
		in.close(); // closing the file
	}
}

Consider another Example to copy one file contents to another file.

import java.io.*;

public class FileCopyExample {

	public static void main(String[] args) throws IOException {

		FileInputStream in = null;
		FileOutputStream out = null;

		in = new FileInputStream("source.txt");
		out = new FileOutputStream("target.txt");
		int c;
		// -1 indicates file ending character
		while ((c = in.read()) != -1) {
			out.write(c);
		}
		if (in != null) { // check if file is opened
			in.close();
		}
		if (out != null) { // check if file is opened
			out.close();
		}
	}
}

A note to eclipse users : The above examples run fine from command line arguments but if you use eclipse, then eclipse copies all the compiled .class files to bin directory of your project. Like :

if your code is in yourproject/src/yourpackage/file.java, then eclipse copies file.class to yourproject/bin/yourpackage/file.class. If you have mentioned file from your current working directory(src) path,then the code will not work. to fix this you have to define path of file from your bin directory, instead of current src directory.