Friday, March 13, 2015

File in java proram



Write string content to a file in java

package com.java2novice.files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class WriteToFile
{
    public static void main(String[] args)
    {
               BufferedWriter bufferedWriter = null;
        try
         {
            String strContent = "This example shows how to write string content to a file";
            File myFile = new File("C:/MyTestFile.txt");
            if (!myFile.exists())
            {
                myFile.createNewFile();
            }
            Writer writer = new FileWriter(myFile);
            bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(strContent);
            }
            catch (IOException e)
           {
            e.printStackTrace();
           }
             finally
            {
            try
           {
                if(bufferedWriter != null) bufferedWriter.close();
            }
           catch(Exception ex){}
        }
    }
}

Delete 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 MyTempDelete
{
           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.");
        tempFile.deleteOnExit();
        tempFile.delete();
    }
}

No comments:

Post a Comment