Friday, March 13, 2015

Java using file program



Write or store data into temporary file in java

package com.java2novice.files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MyTempFileWrite
{    
public static void main(String a[])
{
                 File tempFile = null;
        BufferedWriter writer = null;
        try
           {
            tempFile = File.createTempFile("MyTempFile", ".tmp");
            writer = new BufferedWriter(new FileWriter(tempFile));
            writer.write("Writing data into temp file!!!");
        }
        catch (IOException e)
         {
            e.printStackTrace();
        }
        finally
           {
            try
            {
                if(writer != null) writer.close();
            }
            catch(Exception ex){}
        }
        System.out.println("Stored data in temporary file.");
    }
}

How to create temporary file in java

package com.java2novice.files; 
import java.io.File;
import java.io.IOException;
public class MyTmpFile
    public static void main(String a[])
     {
                  File tmpFile = null;
        try
           {
            tmpFile = File.createTempFile("MyTempFile", ".tmp");
            System.out.println("Created Temp File Location : " + tmpFile.getAbsolutePath());
        }
        catch (IOException e)
           {
            e.printStackTrace();
        }
    }
}

Read a file using BufferedInputStream

package com.java2novice.files;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream; 
public class MyFileReadBybis
         {
          public static void main(String a[])
                {
        InputStream is = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
        try
           {
            is = new FileInputStream("/Users/ngootooru/sample.txt");
            bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
            String temp = null;
            while((temp = dis.readLine()) != null)
            {
                System.out.println(temp);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
         catch (IOException e)
        {
                        e.printStackTrace();
        }
    }
}

No comments:

Post a Comment