用JAVA复制一个已经存在的文本文件,生成一个新文件
时间: 2023-06-19 12:07:51 浏览: 93
你可以使用Java中的FileInputStream和FileOutputStream类来实现复制文件的操作。下面是一个简单的示例代码:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
File sourceFile = new File("source.txt");
File destFile = new File("destination.txt");
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们首先创建一个名为`source.txt`的源文件和一个名为`destination.txt`的目标文件。然后,我们使用FileInputStream类打开源文件,使用FileOutputStream类创建目标文件。接下来,我们使用一个大小为1024字节的缓冲区从源文件中读取数据,并将其写入目标文件中。最后,我们关闭输入和输出流,并打印出复制文件成功的消息。