JAVA高手请进!求一个JAVA程序:将一个文件中的内容复制到另一个文件中。

如题所述

最简单的io流问题,不用什么高手,

我给你写个方法,参数是2个字符串,第一个写原文件的全路径,第二个写目标文件的全路进。 你试试吧

public void copy(String fromFilePath, String toFilePath) {

try {

FileInputStream fis = new FileInputStream(fromFilePath);

FileOutputStream fos = new FileOutputStream(toFilePath);

byte[] b = new byte[100];

try {
while (fis.read(b) != (-1)) {

fos.write(b);
}

if (fis != null) {

fis.close();
fis = null;
}
if (fos != null) {
fos.flush();
fos.close();
fos = null;

}
} catch (IOException e) {

System.out.println("io异常");
}

} catch (FileNotFoundException e) {

System.out.println("源文件不存在");

}

public static void main(String[] args) {

//自己把路径补齐,别忘了!!!!!!!!!!!!!!!!

String fromFilePath=" "; // 源文件的全路径。 比方"d://myphoto//nihao.mp3"

String toFilePath=" "; //目标文件的全路劲。 如果不存在会自动建立,如存在则在文件尾继续添加

new CopyTest().copy(fromFilePath, toFilePath);

}

}
温馨提示:内容为网友见解,仅供参考
第1个回答  2008-10-16
将"中国农民贫穷的真正原因.txt"复制到("d:/MYJAVADemo/fileCopyDemo.txt"
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 FileCopyDemo {

public static void main(String[] args) {
File dir = new File("d:/MYJAVADemo/");
if (dir.exists()) {
System.out.println("目录己经存在: ");
} else {
if (dir.mkdirs()) {
System.out.println("目录生创建成功: ");
} else {
System.out.println("目录生成失败,系统异常退出: ");
System.exit(1);
}
}

File file = new File(dir, "fileCopyDemo.txt");
File file1 = new File(dir, "中国农民贫穷的真正原因.txt");
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream(file);
fis = new FileInputStream(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileChannel filechannel1 = fos.getChannel();
FileChannel filechannel2 = fis.getChannel();

try {
filechannel1.transferFrom(filechannel2, 0, filechannel2.size());
//注意这个方法,输出文件管道向输入文件管道读取数据;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (filechannel1 != null) {
try {
filechannel1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (filechannel2 != null) {
try {
filechannel2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}
第2个回答  2008-10-16
用记事本打开,复制到另一个文件中。
第3个回答  2019-05-13
FileChannel inchannel=FileChannel.open(Paths.get("1.mkv"), StandardOpenOption.READ);
FileChannel outchannel=FileChannel.open(Paths.get("2.mkv"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
inchannel.transferTo(0, inchannel.size(), outchannel);
相似回答