Wednesday, July 27, 2022

How to read from and write to a text file in Java - Example Tutorial

Java has excellent support for reading from file and writing to file in Java. In the last post, we have seen how to create files and directories in Java and now we will see how to read content from files in java and how we will write text into file in Java. File provides a persistent solution to Java developers; 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 the application but without persistence, no enterprise Java application can buildup. 

Normally Database is the preferred choice for storing data persistently but in high-frequency trading one doesn’t have the liberty to afford network latency to travel database and latency introduced by the database itself.

Though databases still offer the best choice for historical data, transactional details related to orders and trades are commonly stored in In-Memory files provided by Java.nio API.

Java NIO API also provides a faster way to read and write from a file in Java using FileChannel, after looking this way you can also try reading file using NIO API and FileChannel by following that example. 




How to read and write from a 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 a 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.


How to read from and write to a text file in Java - Example Tutorial



File read and write Example in Java

read and writ from text file in JavaNow we see a simple example of reading and writing binary data to a file in Java.


class FileStreamsReadnWrite {
public static void 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 a 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 a file in Java and writing data into a file in Java. It’s very important to understand the java.io package to get mastery in java and the best way is to write examples and simple programs and understand concepts.


Java tutorials you may like

7 comments:

  1. If you use this older code (pre Java 7), you should call close() in finally as shown here: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

    Otherwise you can be unpleasantly surprised in case of an exception.

    From Java 7 onwards it's best to use new block "try with resources" as shown here: http://fahdshariff.blogspot.com/2011/07/java-7-try-with-resources.html

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Hello, Can anybody help please?
    I have a file : movies.csv search the data (if movie title make more 100 then write to search.csv file and the end input some comment from the keyboard.
    Title description year amount
    007 Action in 1999 Nov 2012 125
    Halo Action in 2001 May 2013 105
    I"m 4 Action in 2006 June 2010 90

    Make your comment?

    ReplyDelete
  6. your code is not running

    ReplyDelete
  7. @Anonymous, Can you please explain how did you run? What error you are getting? may be I can help you there.

    ReplyDelete