Home > Programming > How to copy text file in Java?

How to copy text file in Java?

January 30th, 2009 Leave a comment Go to comments

Code below demonstrating how to copy data from one text file to another in Java.

This testing method, is calling FileCopier.copyFile(File, File) to copy content of file test1.css to file test2.css

    public static void main(String[] args) {
        FileCopier.copyFile(new File("D:/TEMP/test1.css"), 
                            new File("D:/TEMP/test2.css"));
    }

Class: FileCopier.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class FileCopier {
 
    /**
     * Testing Method
     * @param args
     */
    public static void main(String[] args) {
        FileCopier.copyFile(new File("D:/TEMP/test1.css"), 
                            new File("D:/TEMP/test2.css"));
    }
 
    /**
     * Copy content of file f1 into file f2
     * @param f1
     * @param f2
     */
    public static void copyFile(File f1, File f2) {
        try {
            FileReader in = new FileReader(f1);
            FileWriter out = new FileWriter(f2);
            int line;
            while ((line = in.read()) != -1) {
                // Read line fromtext file and write to destination file
                out.write(line);
            }
            in.close();
            out.close();
 
        } catch (FileNotFoundException ffx) {
            ffx.printStackTrace();
        } catch (IOException iox) {
            iox.printStackTrace();
        }
    }
 
}
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.