Java Tutorial
FileOutputStream(String fileName) throws FileNotFoundExceptionhere fileName specifies the name of the file that we want to write in java program.
void close() throws IOExceptionTo write a file, write method is available in FileOutputStream object.
void write(int byteval) throws IOException
// Java code to read a file and write content in another file // using FileInputStream class import java.io.*; class FileCopyTest { public static void main(String args[]) throws IOException { FileInputStream fin; FileOutputStream fout; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException ex) { System.out.println("File is not found: "+ args[0] + ", error: " + ex.toString()); return; } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("Error: "+ ex.toString()); return; } try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException ex) { System.out.println("File is not found: "+ args[1] + ", error: " + ex.toString()); return; } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("Error: "+ ex.toString()); return; } int byteval; //Copy file into another file. try { while(true) { byteval = fin.read(); //stops loop when reading value -1 which is the end of file character. if(byteval == -1) break; fout.write(byteval); } } catch(IOException ex) { System.out.println("File Error: "+ ex.toString()); } fin.close(); fout.close(); } }Output:
$ javac FileCopyTest.java $ java FileCopyTest input.txt input1.txt // input1.txt file is created with same input.txt file content # Reading Input for java program -------------------------------- Reading line1 Reading line2 Reading line3 -------------------------------
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page