标签:
下面的代码可以实现以字节为单位复制文件的功能,适合复制非文本类型的文件。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
/**
* @param args
*/
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream ("a.jpg");
FileOutputStream fos = new FileOutputStream ("temp.jpg");
int read = fis.read();
while ( read != -1 ) {
fos.write(read);
read = fis.read();
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是,这段代码在复制如mp3等大文件时,运行效率很低,即运行时间长。
下面是改进的代码
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class fileChannelCopy { /** * @param args */ public static void fileChannelCopy(File a ,File b){ FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(a); fo = new FileOutputStream(b); in = fi.getChannel(); out = fo.getChannel(); try { in.transferTo(0, in.size(), out); fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub File a = new File("a.mp3"); File b = new File("temp.jpg"); fileChannelCopy(a,b); } }
标签:
原文地址:http://www.cnblogs.com/guaishoubiubiu/p/5372790.html