Friday, October 31, 2014

Java File Outputstream



Append output to file using File Output Stream

import java.io.*;
public class AppendToFile
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//demo.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath, true);
String strContent = "Append output to a file example";
fos.write(strContent.getBytes());
fos.close();
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
    }
  }
}

Copy binary file using Streams

import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBinaryFile
 {
public static void main(String[] args)
 {
String strSourceFile="C:/FileIO/source.dat";
String strDestinationFile="C:/FileIO/dest.dat";
 try
{
FileInputStream fin = new FileInputStream(strSourceFile); FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1024];
int noOfBytes = 0;                     
System.out.println("Copying file using streams");
while( (noOfBytes = fin.read(b)) != -1 )
{
fout.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
fin.close();
fout.close();                  
}
catch(FileNotFoundException fnf)
{
System.out.println("Specified file not found :" + fnf);
}
catch(IOException ioe)
{
System.out.println("Error while copying file :" + ioe);
     }
  }
}

Create File Output Stream object from File object

import java.io.*;
public class CreateFileOutputStreamObjectFromFile
{
public static void main(String[] args)
{
File file = new File("C://FileIO//demo.txt");
try
{
FileOutputStream fos = new FileOutputStream(file);
}
catch(FileNotFoundException ex)
{
System.out.println("Exception : " + ex);
      }
   }
}

Create File Output Stream object from String file path

import java.io.*;
public class CreateFileOutputStreamObjectFromString
{
 public static void main(String[] args)
{
String strFilePath = "C://FileIO//demo.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
}
catch(FileNotFoundException ex)
{
System.out.println("Exception : " + ex);
     }
   }
}

No comments:

Post a Comment