Reading and Writing files in Java


Reading a File:

/*
* FileInputDemo
* Demonstrates FileInputStream and
* DataInputStream
*/

import java.io.DataInputStream;
import java.io.FileInputStream;

public class FileInputDemo { public static void main(String args[]) {

// args.length is equivalent to argc in C

  if (args.length == 1) {       try {

         // Open the file that is the first
         // command line parameter

         FileInputStream fstream = new FileInputStream(args[0]);
         // Convert our input stream to a DataInputStream

        DataInputStream in = new DataInputStream(fstream);

        // Continue to read lines while there are still some left to read

        while (in.available() != 0) {
         
// Print file line to screen
         
System.out.println(in.readLine());
        }

          in.close();

      } catch (Exception e) {
         System.
err.println(“File input error”);
    }
  } else{
     
System.out.println(“Invalid parameters”);
  }

 }

}

Now we know that readLine method of DataInputStream is depricated. So we can use BufferedReader in this case,

     try {
       BufferedReader br = new BufferedReader(new FileReader(args[0]));
       while ((thisLine = br.readLine()) != null) { // while loop begins here
         System.out.println(thisLine);
       } // end while
     } // end try
     catch (IOException e) {
       System.err.println(“Error: ” + e);
     }

Wrinitg Files in Java:

/*
*
* FileOutputDemo
*
* Demonstration of FileOutputStream and
* PrintStream classes
*
*/

import java.io.*;

class FileOutputDemo
{

        public static void main(String args[])
        {             
                FileOutputStream out; // declare a file output object
                PrintStream p; // declare a print stream object

                try
                {
                        // Create a new file output stream
                        // connected to “myfile.txt”

                        out = new FileOutputStream(“myfile.txt”);

                        // Connect print stream to the output stream
                        p = new PrintStream( out );

                        p.println (“This is written to a file”);

                        p.close();
                }
                catch (Exception e)
                {
                        System.err.println (“Error writing to file”);
                }
        }
}

Now we can also use a relative path to input the file.

Like:

String filePath = System.getProperty(“user.dir”)+ \\log\\;
FileInputStream fstream =
new FileInputStream(filePath + “my-log.txt”);

This code will take the file as input which is in log directory under the main folder and whose name  is my-log.txt.

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s