Java - Streams, Files and I/OThe java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc. A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one: Byte Streams Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream andFileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file:
import java.io.*;
public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile Character Streams Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Characterstreams are used to perform input and output for 16 -bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file:
import java.io.*;
public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile Standard Streams All the programming languages provide support for standard I/O where user's program can take input from a keyboard and then produce output on the computer screen. If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams
import java.io.*;
public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } } } Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole Enter characters, 'q' to quit. 1 1 e e q q Reading and Writing Files: As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams. The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial: FileInputStream: This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available. Following constructor takes a file name as a string to create an input stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f); Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.
The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array. There are following forms of constructors to create ByteArrayInputStream objects Takes a byte array as the parameter:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another form takes an array of bytes, and two ints, where off is the first byte to be read and len is the number of bytes to be read.
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,
int off, int len) Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.
Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream
import java.io.*;
public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // Gets the inputs from the user bOutput.write(System.in.read()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x= 0 ; x < b.length; x++) { // printing the characters System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayInputStream bInput = new ByteArrayInputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c= bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } } Here is the sample run of the above program:
asdfghjkly
Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y DataInputStream The DataInputStream is used in the context of DataOutputStream and can be used to read primitives. Following is the constructor to create an InputStream:
InputStream in = DataInputStream(InputStream in);
Once you have DataInputStream object in hand, then there is a list of helper methods, which can be used to read the stream or to do other operations on the stream.
Following is the example to demonstrate DataInputStream and DataInputStream. This example reads 5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class Test{ public static void main(String args[])throws IOException{ DataInputStream d = new DataInputStream(new FileInputStream("test.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt")); String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + " ,"); } d.close(); out.close(); } } Here is the sample run of the above program:
THIS IS TEST 1 ,
FileOutputStream:THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 , THIS IS TEST 5 , FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object. Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f); Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.
The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer. There are following forms of constructors to create ByteArrayOutputStream objects Following constructor creates a buffer of 32 byte:
OutputStream bOut = new ByteArrayOutputStream()
Following constructor creates a buffer of size int a:
OutputStream bOut = new ByteArrayOutputStream(int a)
Once you have ByteArrayOutputStream object in hand then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
Following is the example to demonstrate ByteArrayOutputStream and ByteArrayOutputStream
import java.io.*;
public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // Gets the inputs from the user bOutput.write(System.in.read()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x= 0 ; x < b.length; x++) { //printing the characters System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayOutputStream bInput = new ByteArrayOutputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c= bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } } Here is the sample run of the above program:
asdfghjkly
Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y DataOutputStream The DataOutputStream stream let you write the primitives to an output source. Following is the constructor to create a DataOutputStream.
DataOutputStream out = DataOutputStream(OutputStream out);
Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write the stream or to do other operations on the stream.
Following is the example to demonstrate DataInputStream and DataOutputStream. This example reads 5 lines given in a file test.txt and converts those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class Test{ public static void main(String args[])throws IOException{ DataInputStream d = new DataInputStream(new FileInputStream("test.txt")); DataOutputStream out = new DataOutputStream( new FileOutputStream("test1.txt")); String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + " ,"); } d.close(); out.close(); } } Here is the sample run of the above program:
THIS IS TEST 1 ,
THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 , THIS IS TEST 5 , Example: Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
public class fileStreamTest{ public static void main(String args[]){ try{ byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x=0; x < bWrite.length ; x++){ os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i=0; i< size; i++){ System.out.print((char)is.read() + " "); } is.close(); }catch(IOException e){ System.out.print("Exception"); } } } The above code would create file test.txt and would write given numbers in binary format. Same would be output on the stdout screen. File Navigation and I/O: There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc. The File object represents the actual file/directory on the disk. There are following constructors to create a File object: Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.
File(File parent, String child);
Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.
File(String pathname)
Following syntax creates a new File instance from a parent pathname string and a child pathname string.
File(String parent, String child)
Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.
File(URI uri)
Once you have File object in hand then there is a list of helper methods which can be used manipulate the files.
Following is the example to demonstrate File object:
package com.tutorialspoint;
import java.io.File; public class FileDemo { public static void main(String[] args) { File f = null; String[] strs = {"test1.txt", "test2.txt"}; try{ // for each string in string array for(String s:strs ) { // create new file f= new File(s); // true if the file is executable boolean bool = f.canExecute(); // find the absolute path String a = f.getAbsolutePath(); // prints absolute path System.out.print(a); // prints System.out.println(" is executable: "+ bool); } }catch(Exception e){ // if any I/O error occurs e.printStackTrace(); } } } Consider there is an executable file test1.txt and another file test2.txt is non executable in current directory, Let us compile and run the above program, this will produce the following result:
test1.txt is executable: true test2.txt is executable: false
FileReader Class This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters. This class has several constructors to create required objects. Following syntax creates a new FileReader, given the File to read from.
FileReader(File file)
Following syntax creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)
Following syntax creates a new FileReader, given the name of the file to read from.
FileReader(String fileName)
Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.
Following is the example to demonstrate class:
import java.io.*;
public class FileRead{ public static void main(String args[])throws IOException{ File file = new File("Hello1.txt"); creates the file file.createNewFile(); creates a FileWriter Object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This\n is\n an\n example\n"); writer.flush(); writer.close(); //Creates a FileReader Object FileReader fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); //prints the characters one by one fr.close(); } } This would produce the following result:
This
is an example FileWriter Class This class inherits from the OutputStreamWriter class. The class is used for writing streams of characters. This class has several constructors to create required objects. Following syntax creates a FileWriter object given a File object.
FileWriter(File file)
Following syntax creates a FileWriter object given a File object.
FileWriter(File file, boolean append)
Following syntax creates a FileWriter object associated with a file descriptor.
FileWriter(FileDescriptor fd)
Following syntax creates a FileWriter object given a file name.
FileWriter(String fileName)
Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
FileWriter(String fileName, boolean append)
Once you have FileWriter object in hand, then there is a list of helper methods, which can be used manipulate the files.
Following is the example to demonstrate class:
import java.io.*;
public class FileRead{ public static void main(String args[])throws IOException{ File file = new File("Hello1.txt"); creates the file file.createNewFile(); creates a FileWriter Object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This\n is\n an\n example\n"); writer.flush(); writer.close(); //Creates a FileReader Object FileReader fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); //prints the characters one by one fr.close(); } } This would produce the following result:
This
is an example Directories in Java: A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail check a list of all the methods which you can call on File object and what are related to directories. Creating Directories: There are two useful File utility methods, which can be used to create directories:
import java.io.File;
public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirname); // Create directory now. d.mkdirs(); } } Compile and execute above code to create "/tmp/user/java/bin". Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly. Listing Directories: You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows:
import java.io.File;
public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try{ // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } }catch(Exception e){ // if any error occurs e.printStackTrace(); } } } This would produce following result based on the directories and files available in your /tmp directory:
test1.txt
test2.txt ReadDir.java ReadDir.class |