Learning Resources
File I/O
The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system. Though the API has many classes, you need to focus on only a few entry points. You will see that this API is very intuitive and easy to use.
The tutorial starts by asking what is a path? Then, the Path class, the primary entry point for the package, is introduced. Methods in the Path class relating to syntactic operations are explained. The tutorial then moves on to the other primary class in the package, the Files class, which contains methods that deal with file operations. First, some concepts common to many file operations are introduced. The tutorial then covers methods for checking, deleting, copying, and moving files.
The tutorial shows how metadata is managed, before moving on to file I/O and directory I/O. Random access files are explained and issues specific to symbolic and hard links are examined.
Next, some of the very powerful, but more advanced, topics are covered. First, the capability to recursively walk the file tree is demonstrated, followed by information about how to search for files using wild cards. Next, how to watch a directory for changes is explained and demonstrated. Then, methods that didn't fit elsewhere are given some attention.
Finally, if you have file I/O code written prior to the Java SE 7 release, there is a map from the old API to the new API, as well as important information about the File.toPath method for developers who would like to leverage the new API without rewriting existing code.
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.
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.
SN | Methods with Description |
---|---|
1 |
public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. |
2 |
protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. |
3 |
public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file. |
4 |
public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned. |
5 |
public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int. |
There are other important input streams available, for more detail you can refer to the following links:
-
ByteArrayInputStream
-
DataInputStream
FileOutputStream:
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.
SN | Methods with Description |
---|---|
1 |
public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. |
2 |
protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. |
3 |
public void write(int w)throws IOException{} This methods writes the specified byte to the output stream. |
4 |
public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream. |
There are other important output streams available, for more detail you can refer to the following links:
-
ByteArrayOutputStream
-
DataOutputStream
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("C:/test.txt"); for(int x=0; x < bWrite.length ; x++){ os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("C:/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.
-
File Class
-
FileReader Class
-
FileWriter Class
Directories in Java:
Creating Directories:
There are two useful File utility methods which can be used to create directories:
-
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
-
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File; 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.
Reading Directories:
A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory( ) method will return true.
You can call list( ) on that object to extract the list of other files and directories inside. The program shown here illustrates how to use list( ) to examine the contents of a directory:
import java.io.File; class DirList { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println( "Directory of " + dirname); String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + "/" + s[i]); if (f.isDirectory()) { System.out.println(s[i] + " is a directory"); } else { System.out.println(s[i] + " is a file"); } } } else { System.out.println(dirname + " is not a directory"); } } } |
This would produce following result:
Directory of /mysql bin is a directory lib is a directory demo is a directory test.txt is a file README is a file index.html is a file include is a directory |