怎么用BufferedReader和BufferedWriter、BufferedInputStream和BufferedOutputStream类对文件进行复制。
时间: 2023-12-25 15:23:37 浏览: 70
可以使用以下代码来使用BufferedReader和BufferedWriter类对文件进行复制:
```
try (BufferedReader reader = new BufferedReader(new FileReader("source.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("destination.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
```
使用BufferedInputStream和BufferedOutputStream类对文件进行复制的代码如下:
```
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("source.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("destination.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
```
这些代码使用了缓冲流来提高文件复制的效率,同时使用了try-with-resources语句来自动关闭流。
阅读全文