Oi pessoal,
Desenvolvi um projeto com algumas classes e métodos para facilitar a vida no que diz respeito a operações de IO.
Exportei como arquivo jar.
Para fazer minha classe CopiaArquivo, por exemplo, utilizei a classe FileChannel da api do java.
Depois de terminar o projeto me dei conta que havia utilizado esta classe arbitrariamente, sem me preocupar se este seria o melhor jeito.
Então resolvi fazer uns testes, comparando a classe FileChannel com as clássicas Bufffered.
Vejam o seguinte código:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.util.Date;
public class Main {
public static void main(String[] args)throws IOException {
long inicioChannels = new Date ().getTime();
testWithChannels();
long terminoChannels = new Date().getTime();
System.out.println ("Tempo channels: " + (terminoChannels - inicioChannels));
long inicioBuffered = new Date ().getTime();
testWithBufferedClasses();
long terminoBuffered = new Date().getTime();
System.out.println ("Tempo Buffered: " + (terminoBuffered - inicioBuffered));
new File ("D:\\destinoChannel\\testePerformance.txt").delete();
new File ("D:\\destinoBuffered\\testePerformance.txt").delete();
}
private static void testWithChannels ()throws IOException{
FileChannel srcChannel = new FileInputStream("D:\\origemChannel\\testePerformance.txt").getChannel();
FileChannel dstChannel = new FileOutputStream("D:\\destinoChannel\\testePerformance.txt").getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();
}
private static void testWithBufferedClasses ()throws IOException{
BufferedReader reader = new BufferedReader (new FileReader (new File ("D:\\origemBuffered\\testePerformance.txt")));
PrintWriter writer = new PrintWriter (new FileWriter (new File ("D:\\destinoBuffered\\testePerformance.txt")));
char [] buffer = new char [1024];
int lido = 0;
while ((lido = reader.read(buffer)) != -1){
writer.write(buffer);
}
writer.flush();
writer.close();
reader.close();
}
}
Conclusões do teste:
Para arquivos pequenos, de até 100 Kb, o tempo de execução de ambos os métodos é praticamente o mesmo.
Para arquivos maiores, o método que usa a classe FileChannel começa a levar vantagem.
Com um arquivo de 15 megas, o tempo de fileChannel foi 200 e o das classe Buffered foi 800. E esta diferença aumenta conforme aumenta o tamanho do arquivo.
Também testei colocar BufferedWriter no lugar de PrintWriter. O tempo piorou drasticamente.
