Java Development
Articles
Copying Files in Java
Published: September 3, 2007
Print    Email

In this tutorial, author discusses how to use java class to copy files.

First example: Copy file using FileWriter

FileWriter is convenience class for writing character files. The constructors of FileWriter  assume that the default character encoding and the default byte-buffer size are acceptable

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFile {
  public static void main(String[] args) throws IOException {
    File inputFile = new File("inputfile.txt");
    File outputFile = new File("outfile.txt");
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;
    while ((c = in.read()) != -1)
     out.write(c);
    in.close();
    out.close();
  }
}

Second example:copy files using FileChannel class

FileChannel provides a channel for reading, writing, mapping, and manipulating a file.

import java.io.*;
import java.nio.channels.*;
public class FileCopy {
    public static void main(String[  ] args) {
        FileInputStream fin = null;  
        FileOutputStream fout = null;
        try {
            fin = new FileInputStream(args[0]);
            FileChannel in = fin.getChannel( );
            WritableByteChannel out;
            if (args.length > 1) {
                fout = new FileOutputStream(args[1]); 
                out = fout.getChannel( );             
            }
            else {
                out = Channels.newChannel(System.out);
            }
            long numbytes = in.size( );
            in.transferTo(0, numbytes, out);
        }
        catch(IOException e) {
            System.out.println(e);
        }
        finally {
            try {
                if (fin != null) fin.close( );
                if (fout != null) fout.close( );
            }
            catch(IOException e) {  }
        }
    }
}



View Comments (0)
Latest Articles
Java Threads

Delete file using File.delete( ) method

Copying Files in Java

Downloading the Contents of a URL

Java FTP Source Code

Processing XML with Java

Generating Random Numbers

Java Lexical Structure

Serializing

Learning java
Latest Posts
Last news from Bahrain islands
Posted by ribrothetit

Please, help me
Posted by FthrOfIIIChlds

Beginners tutorial!
Posted by perz

Health and Beauty FOREVER
Posted by SKACTANDATE

buy xanax fergana
Posted by FleseeKip

Users Online
Online Now: 4
0 Members | 4 Guests

Most users ever online was 74 on November 6, 2007 at 13:07 PM.
Newsletter
Subscribe to our Newsletter!

Your Email: