Tuesday, December 6, 2011

Java has excellent support for reading from file and writing to file in Java. In last post we have seen how to create file and directory in Java and now we will see how to read content from file in java and how we will write text into file in Java. File provides persistent solution to Java developer; in almost every Java application you need to store some of the data in persistent may be its user configuration, system configuration or related to state of application but without persistence no enterprise Java application can buildup. Normally Database is preferred choice for storing data persistently but in high frequency trading one doesn’t have liberty to afford network latency to travel database and latency introduced by database itself, though database still offer best choice for historical data , transactional details related to orders and trades are commonly stored in In Memory files provided by Java.nio API.

How to read and write from text file in Java

Though in this java file tutorial we are not talking about In Memory files, we will discuss plain old File classes and how to read and write into File in Java by using java.io package classes.

If we are working on Standalone application then we have access to local file system and we can easily using the java API read and write on files, but we if we our application is running on browser based system then this will not work. If we are using input and output stream for reading and writing it’s very easy to understand. We have to follow three simple steps to achieve this task.

ØFirst get the File object

ØCreate the File Stream from File object

ØUse this File Stream for reading or writing the data to the file in the file system.

Apart from this we need to remember some points which should be taken care at the time of reading and writing to the file in Java.

ØAlways try to use reference of abstract classes or interfaces in place of implemented class or we can say concrete class it is a one of the good java practice also.

ØIf needed use buffering it’s a good practice because calling a read() method for single byte JVM will call the native operating system method and calling a operating system method is expensive so Buffering will reduce this overhead from some extent.

ØIf using buffer then mentions the buffer size also it will affect the read time and CPU time also.

ØAlways Handle the Exceptions (IOException and FileNotFoundException)

ØDon’t forget to call close() method for resource which we are using such as File or Directory in Java. You can also use automatic resource management in JDK7 to automatically close any open resource in Java.

File read and write Example in Java

Now we see simple example of reading and writing a binary data to a file in Java.

class FileStreamsReadnWrite {

publicstaticvoid main(String[] args) {

try {

File stockInputFile = new File("C://stock/stockIn.txt");

File StockOutputFile = new File("C://stock/StockOut.txt");

/*

* Constructor of FileInputStream throws FileNotFoundException if

* the argument File does not exist.

*/

FileInputStream fis = new FileInputStream(stockInputFile);

FileOutputStream fos = new FileOutputStream(StockOutputFile);

int count;

while ((count = fis.read()) != -1) {

fos.write(count);

}

fis.close();

fos.close();

} catch (FileNotFoundException e) {

System.err.println("FileStreamsReadnWrite: " + e);

} catch (IOException e) {

System.err.println("FileStreamsReadnWrite: " + e);

}

}

}

This is very simple example where we are reading from stockInputfile and whatever contents are there we are writing that to stockoutput file one important point here is that FileInputStream should not be used to read character data file.It is meant for reading binary data such as an image file.

That’s all on how to read from file in Java and writing data into file in Java. It’s very important to understand java.io package to get mastery in java and best way it to write examples and simple program and understand concept.

Thanks farhan for you comment, Indeed read and write in file is important and what is even more important is exception handling while dealing with files and IO. Java has made IOException checked just for that reason so that every Java program which opens files for reading and writing must close its file descriptor to avoid locking of file in OS.

How different it is to read a text file than to any other file e.g. xml or binary using FileInputStream or any other means ? In reality they all read files byte by byte but may or may not provide access to those bytes. One important point while reading file to remember is encoding, if you use different encoding while reading file then you don't get correct content. Always check encoding of file before reading it to ensure that you are using correct file encoding.

What is the maximum size of text file which one can read in Java program in 32 bit windows machine ? I guess its not 4Gig but way less than that. Also there is another way of reading text file, by using Scanner you can easily read them without any hassle of creating BufferedInputStream.