用java编写程序拷贝一个文件.

2024-12-15 18:42:41
推荐回答(3个)
回答1:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {

public static void main(String[] args) throws IOException {

String src = null;
String desc = null;
try{
src = args[0];
desc = args[1];
}catch(ArrayIndexOutOfBoundsException noFileExp){
System.out.println("请传递要拷贝的文件名字");
return;
}

FileInputStream srcFile = new FileInputStream(src);
FileOutputStream descFile = new FileOutputStream(desc);

byte[] ary = null;
int byteRead = -1;
do{
ary = new byte[1024];

byteRead = srcFile.read(ary);

descFile.write(ary);
descFile.flush();
}while(byteRead != -1);

srcFile.close();
descFile.close();
}

}

----------------------testing

C:\Program Files\IBM\RAD 7\jdk\bin>java FileCopy.class c:\aa.jpg c:\cc.jpg

C:\Program Files\IBM\RAD 7\jdk\bin>

回答2:

private void copyFile(File f, File dir) // 将文件f(f是一个带有路径的文件名)复制到dir(是一个目录路径)目录下
{

if (!f.isFile())
System.out.println("这不是文件!");
else {
try {
File fcopy = new File(dir, f.getName());
fcopy.createNewFile();
FileInputStream finpen = new FileInputStream(f);
FileOutputStream foutpen = new FileOutputStream(fcopy);
FileChannel fin = finpen.getChannel(), fou = foutpen
.getChannel();

ByteBuffer byb = ByteBuffer.allocate(1024);
int i = 1;
while (i != -1) {
byb.clear();
i = fin.read(byb);
byb.flip();
fou.write(byb);
}
fin.close();
fou.close();
finpen.close();
foutpen.close();
} catch (Exception e) {
System.out.println("复制文件出错。建议检查文件的属性。");
}
}
}

回答3:

格的