Monday, 12 September 2011

Java: Reading from a file

    To read data from a file, you need to first open up the file in question, using the file's name. This is to establish a connection between the program and the file. At this point, do what you want to do with the data (In our case, read it), and finally, when done, you need to close the file! This is important! Closing an already closed file doesn't do anything, and everything is just dandy, but to make sure you clean up after yourself, always close the file.

    We'll be using input streams and a buffered reader to read our files. A data input stream is for reading primitive data types from an underlying input stream (FileInputStream in our case). You can probably guess to write data into a file, we'll then be using a data output stream.

    BufferedReader is what we'll use to read text from the input stream, buffering characters to more efficiently read characters and lines. The buffer size CAN be specified, but, being a relative simpleton, I'll just stick with using the default. It's never steered me wrong.

    I created a file with random crap and named it DataFileInfo.txt, this is what we'll be trying to read from.  For reference, the file's contents are:


    Not exactly thought provoking, I know.So without further ado, here's how to read in data!

import*;   //This is required for the streams etc.
                              //IO stands for input/output
                              //The star is a wildcard. It imports everything from io.

public class DataFiles {

    public static void readFile(String fileName) throws FileNotFoundException, IOException {
        // the "throws..." you see after the parameters are to do with errors that may
        //arise. Your IDE should automatically let you know when you need to put one up.
        //Exceptions and errors come later, so we'll just sit content at how it is, for now

         //This opens the file passed as the parameter
        FileInputStream fileStream = new FileInputStream(fileName);
         //Get the object into a buffered reader through a datastream
        DataInputStream dataStream = new DataInputStream( fileStream );
        BufferedReader bReader = new BufferedReader( new InputStreamReader( dataStream ) );
         //I know its a pain, and I don't really like it, or even fully understand it
        //but it works, so I guess that's good enough?

        String nextLine;   
        int lineNumber = 1;

        while (( nextLine = bReader.readLine() ) != null) {
        // Having a statement as the condition just means the statement is repeated on each iteration.
        // "null" means nothing, no type, completely empty. When readLine() returns null, not even
        // a new line is present, thus you've reached the end of the file, at which point we want to           
        // stop reading.
            System.out.println( "Line " + lineNumber + ": " + nextLine );

        bReader.close() //Almost forgot this myself.


    public static void main(String[] argv) throws FileNotFoundException, IOException {

        //Insert the full filename here, making sure to use 2 backslashes. Normally,
        //the backslash is used to denote special characters ("\n" and "\t" being 2 we already know)
        //so "\\" displays as just "\". This probably isn't an issue on OSes that use forward slashes

    The output of the above program should be as follows:

 Line 1: Hello
Line 2: safjdbs;1kj1!23
Line 3: 2132141
Line 4: 12.2345
Line 5: s

    ...which it is, so, great! This has taken much longer than expected, so:

    That's it for tonight. Follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us.     
     Mostly me, since he put me in charge of new uploads.

1 comment:

  1. That's pretty neat, thanks!
    Come check me out =)