Java函数实现文件的复制和剪切功能
发布时间:2023-07-04 08:13:35
Java中实现文件的复制和剪切功能,可以使用File类和IO流实现。
1. 文件的复制功能可以使用InputStream和OutputStream来实现。首先需要创建一个输入流来读取源文件的内容,然后创建一个输出流将读取到的内容写入目标文件中。具体实现代码如下:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourcePath = "source.txt"; // 源文件路径
String targetPath = "target.txt"; // 目标文件路径
try {
// 创建输入流
FileInputStream fis = new FileInputStream(sourcePath);
// 创建输出流
FileOutputStream fos = new FileOutputStream(targetPath);
byte[] buffer = new byte[1024];
int bytesRead;
// 读取源文件内容并将其写入目标文件
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
// 关闭流
fis.close();
fos.close();
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 文件的剪切功能可以通过复制后再删除源文件来实现。在复制完成后,需要使用File类的delete()方法删除源文件。具体实现代码如下:
import java.io.*;
public class FileCut {
public static void main(String[] args) {
String sourcePath = "source.txt"; // 源文件路径
String targetPath = "target.txt"; // 目标文件路径
try {
// 创建输入流
FileInputStream fis = new FileInputStream(sourcePath);
// 创建输出流
FileOutputStream fos = new FileOutputStream(targetPath);
byte[] buffer = new byte[1024];
int bytesRead;
// 读取源文件内容并将其写入目标文件
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
// 关闭流
fis.close();
fos.close();
// 删除源文件
File sourceFile = new File(sourcePath);
if (sourceFile.delete()) {
System.out.println("文件剪切成功!");
} else {
System.out.println("文件剪切失败!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过上述代码,可以实现Java中文件的复制和剪切功能。使用FileInputStream和FileOutputStream实现文件的复制,通过复制后再删除源文件实现文件的剪切。
