第四次作业
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); } }