Sep 13, 2012

How To Make a Copy of File in Java

In this simple example, a file is loaded into a stream, copy it into a temporary storage called "temp", from which it was emptied bit by bit to a new directory.



 
package codecypherprojects;

/**
 *
 * @author Khamis
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            File file = new File("c:/FileFolder/cypherexample.txt");

            //A file "cypherexample.txt" is loaded into  stream 
            in = new FileInputStream(file);

            //Here a new text file is created called "newcypherexample.text"
            out = new FileOutputStream("c:/FileFolder/newcypherexample.txt");

           //We need a temporary storage for this read & write operation
            int temp;            
            
            while ((temp = in.read()) != -1) {
                out.write(temp);
                System.out.print(out);
            }
        } finally {
        //close the streams as we are done with them if they still exists
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

Related Posts 

 

No comments:

Post a Comment