需求:实现文件的copy
练习目的:
-
了解JavaNIO知识,主要是关注一下FileInputStream,FileChannel,FileOutputStream,ByteBuffer 之间的关系
-
了解如何获取FileChannel
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public class CopyFile {
public static void main(String[] args) throws Exception {
String inFile = "gitHub.txt";
String outFile = "gitHub2.txt";
//获取源文件和目标文件的输入流、输出流
FileInputStream fin = new FileInputStream(inFile);
FileOutputStream fout = new FileOutputStream(outFile);
//获取输入、输出通道
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
//创建缓存区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
//清楚缓存区的数据,可以接收新的数据
buffer.clear();
//从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
//read方法返回读取的字节数,可能为0, 如果该通道已经达到流的末尾,则返回-1
if (r == -1) {
break;
}
//flip方法,让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
//从缓存区 将数据写到 输出通道里
fcout.write(buffer);
}
//最后关闭
fcin.close();
fout.close();
}
} |
总结如下:
-
数据的流向:
-
什么时候调用FileChannel的read,write方法?
根据数据的方向来确定
本文转自故新51CTO博客,原文链接: http://blog.51cto.com/xingej/1968417,如需转载请自行联系原作者