已知E:\yxy\java路径下存在testin.txt文件。 (提示:需要先手动在E:\yxy\java路径下创建testin.txt文件,文件内要有适量字符内容) 用java编写程序实现,将testin.txt复制到D:\myfile文件夹中。D:\myfile不存在,需要创建,复制的文件名命名“copytestin.txt”.
时间: 2024-02-05 15:09:45 浏览: 19
好的,我可以帮你写一个简单的Java程序来实现这个需求。请确认你的电脑上已经安装了Java环境。
代码如下:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourcePath = "E:\\yxy\\java\\testin.txt";
String destPath = "D:\\myfile\\copytestin.txt";
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
try {
// 判断源文件是否存在
if (!sourceFile.exists()) {
System.out.println("源文件不存在!");
return;
}
// 判断目标文件夹是否存在,不存在则创建
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
// 创建输入输出流
InputStream is = new FileInputStream(sourceFile);
OutputStream os = new FileOutputStream(destFile);
// 缓冲区
byte[] buffer = new byte[1024];
int length;
// 读入数据并写入目标文件
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// 关闭输入输出流
is.close();
os.close();
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
将代码保存为FileCopy.java文件,然后在命令行中执行以下命令进行编译:
```
javac FileCopy.java
```
编译成功后,执行以下命令运行程序:
```
java FileCopy
```
程序会将E:\yxy\java\testin.txt文件复制到D:\myfile\copytestin.txt,如果D:\myfile文件夹不存在,程序会自动创建。复制成功后会在控制台输出"文件复制成功!"。