// Create channel on the source FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); // Create channel on the destination FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); // Copy file contents from source to destination dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); // Close the channels srcChannel.close(); dstChannel.close();
如果文件比较大呢?比如说有10G ?这样会OutOfMemory
我也写过一些,写了一个关于使用FileInputStream ;FileOutputStream来复制一个文件, 写的不怎么地, 希望多少有点帮助; public class CopyFile { public static void main(String[] args) throws IOException { int i; FileInputStream fin; FileOutputStream fou; try { fin = new FileInputStream("d:/data/Hi.java"); } catch (FileNotFoundException e) { System.out.println("Input File Not Found"); return; } try { fou = new FileOutputStream("d:/data/Array.java"); } catch (FileNotFoundException e) { System.out.println("Error Opening Output File"); return; } try { do { i = fin.read(); if (i != -1) fou.write(i); } while (i != -1); } catch (IOException e) { System.out.println("File Error"); } fin.close(); fou.close(); }}
谢谢你的回复 非常抱歉没能及时答复你能给个FileChannel复制大文件的例子吗?
FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); // Create channel on the destination
FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); // Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); // Close the channels
srcChannel.close();
dstChannel.close();
如果文件比较大呢?比如说有10G ?这样会OutOfMemory
写的不怎么地, 希望多少有点帮助;
public class CopyFile {
public static void main(String[] args) throws IOException {
int i;
FileInputStream fin;
FileOutputStream fou; try {
fin = new FileInputStream("d:/data/Hi.java");
} catch (FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
} try {
fou = new FileOutputStream("d:/data/Array.java");
} catch (FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
} try {
do {
i = fin.read();
if (i != -1)
fou.write(i);
} while (i != -1);
} catch (IOException e) {
System.out.println("File Error");
}
fin.close();
fou.close(); }}
谢谢 但是我需要的是FileChannel的例子
在此多问一句:*Reader不适合复制文件(如果不知道是何种文件的情况下)?哪些文件时文本文件,哪些是二进制文件?
你的方法适用于复制小一些的文件,为复制很大的文件,修改了你的方法:public static void copy3() throws Exception {
long start = System.currentTimeMillis();
System.out.println("start");
FileChannel channel = new FileInputStream("E:\\test\\JDK6API.chm").getChannel();
FileChannel channel_out = new FileOutputStream("D:\\JDK6API.chm").getChannel(); long fileSize = channel.size();
int c = 1024000;
long end = 0;
for(long i=0; end<fileSize; i++) {
System.out.println(i);
if((i+1)*c >= fileSize) {
end = fileSize;
} else {
end =(i+1)*c;
}
channel_out.transferFrom(channel, i*c, end);
}
channel.close();
channel_out.close();
long endTime = System.currentTimeMillis();
System.out.println(endTime -start);
}
但是用这个方法复制出错,不管大文件还是小文件,复制后都出问题不知哪里写的不对?