Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.nio.channels.FileChannel;
- import java.util.Random;
- import static java.nio.channels.Channels.*;
- public class MainClass {
- static void genFile(File file){
- try {
- System.out.println("Generating file");
- OutputStream stream = new FileOutputStream(file);
- long size = 400000000;
- long position = 0;
- byte[] buffer = new byte[10*1024];
- Random rnd = new Random();
- for (int i = 0; i < buffer.length; i++){
- buffer[i] = (byte)rnd.nextInt();
- }
- while (position<size){
- stream.write(buffer);
- position += buffer.length;
- }
- stream.close();
- System.out.println("Done");
- } catch (IOException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- static void copyFileBlocks(File input, File output) throws IOException{
- InputStream inp = new FileInputStream(input);
- OutputStream outp = new FileOutputStream(output);
- byte[] buffer = new byte[128*1024];
- while (inp.available()>0){
- int read = inp.read(buffer);
- outp.write(buffer,0,read);
- }
- inp.close();
- outp.close();
- }
- static void copyFileNIO(File input, File output) throws IOException{
- FileInputStream inp = new FileInputStream(input);
- FileOutputStream outp = new FileOutputStream(output);
- FileChannel reader = inp.getChannel();
- FileChannel writer = outp.getChannel();
- long position = 0;
- while (position<reader.size()){
- position+=reader.transferTo(position, 128*1024, writer);
- }
- inp.close();
- outp.close();
- }
- static void copyFileNIOSingle(File input, File output) throws IOException{
- FileInputStream inp = new FileInputStream(input);
- FileOutputStream outp = new FileOutputStream(output);
- FileChannel reader = inp.getChannel();
- FileChannel writer = outp.getChannel();
- reader.transferTo(0, reader.size(), writer);
- inp.close();
- outp.close();
- }
- public static void main(String[] argv){
- try {
- genFile(new File("input.dat"));
- long tick;
- for (int i = 0; i < 5; i++){
- tick = System.currentTimeMillis();
- copyFileBlocks(new File("input.dat"), new File("output1.dat"));
- System.out.println("copyFileBlocks took "+(System.currentTimeMillis() - tick));
- tick = System.currentTimeMillis();
- copyFileNIO(new File("input.dat"), new File("output2.dat"));
- System.out.println("copyFileNIO took "+(System.currentTimeMillis() - tick));
- tick = System.currentTimeMillis();
- copyFileNIOSingle(new File("input.dat"), new File("output3.dat"));
- System.out.println("copyFileNIOSingle took "+(System.currentTimeMillis() - tick));
- }
- } catch (IOException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement