Friday, July 18, 2014

GUAVA: Copy or move a file

Normally this is the code in order to copy a file in Java:
import java.io.*;

public class CopyFileExample {
    public static void main(String[] args) {

        File original = new File("src/main/resources/sampleTextFileOne.txt");
        File copy = new File("src/main/resources/copy.txt");
        byte[] buffer = new byte[1024];
        FileInputStream is = null;
        FileOutputStream os = null;
        int numberRead;
        try {
            is = new FileInputStream(original);
            os = new FileOutputStream(copy, false);
            while((numberRead = is.read(buffer))!= -1){
                os.write(buffer,0,numberRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                is.close();
                os.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

Using Guava API, it's so simple:
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        File original = new File("src/main/resources/sampleTextFileOne.txt");
        File copy = new File("src/main/resources/copy.txt");

        try {
            Files.copy(original, copy);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Similarly to move a file using Files.move method.
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        File original = new File("src/main/resources/sampleTextFileOne.txt");
        File newFile = new File("src/main/resources/copy.txt");

        try {
            Files.move(original, newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment