计算机的人都知道 IO操作是很消耗时间的,所以很多时候我们写IO程序性能慢时都应该从IO操作来找原因,改善我们的IO操作代码,说白了就是用缓存,减少IO操作。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Test {
public static void main(String[] args) {
String sourcePath = "c:/temp.jpg";
String targetPath = "c:/temp2.jpg";
noCacheCopy(sourcePath,targetPath);
cacheCopy(sourcePath,targetPath);
}
public static void noCacheCopy(String sourcePath, String targetPath) {
try {
InputStream inputStream = new FileInputStream(new File(sourcePath));
OutputStream outputStream = new FileOutputStream(new File(targetPath));
int data = inputStream.read();
while( data!=-1)
{
outputStream.write(data);
data = inputStream.read();
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
public static void cacheCopy(String sourcePath, String targetPath) {
try {
InputStream inputStream = new FileInputStream(new File(sourcePath));
OutputStream outputStream = new FileOutputStream(new File(targetPath));
int bufferSize = 1024*4;
final byte[] buffer = new byte[bufferSize];
int n = 0;
while ( -1 != ( n = inputStream.read( buffer ) ) )
{
outputStream.write( buffer, 0, n );
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
}