用两种方法实现文件的拷贝功能。 ①用FileInputStream/FileOutputStream ②用BufferedInputStream/BufferedOutputStream
时间: 2023-12-04 19:40:44 浏览: 72
C#拷贝文件简单实现方法
以下是两种实现文件拷贝功能的方法:
1.使用FileInputStream/FileOutputStream:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("source.txt");
FileOutputStream output = new FileOutputStream("target.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
System.out.println("文件拷贝成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2.使用BufferedInputStream/BufferedOutputStream:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
BufferedInputStream input = new BufferedInputStream(new FileInputStream("source.txt"));
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("target.txt"));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
System.out.println("文件拷贝成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文