java 利用字节流将一个文本的内容复制到另一个文本中
时间: 2023-12-02 13:05:20 浏览: 164
可以使用Java的字节流来实现将一个文本的内容复制到另一个文本中的操作。具体代码如下所示:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourcePath = "source.txt"; // 源文件路径
String destPath = "dest.txt"; // 目标文件路径
try (FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destPath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
首先,我们需要定义源文件路径和目标文件路径。然后,通过`FileInputStream`和`FileOutputStream`来创建文件输入流和输出流。
接下来,我们使用`while`循环来读取源文件中的内容,并将其写入目标文件中。在循环中,我们定义了一个缓冲区`buffer`,每次读取`buffer.length`个字节的数据,并将其写入目标文件。最后,我们需要关闭输入流和输出流。
这样,我们就可以使用Java的字节流将一个文本的内容复制到另一个文本中了。
阅读全文
相关推荐














