-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelCopy.java
More file actions
31 lines (29 loc) · 1.07 KB
/
Copy pathChannelCopy.java
File metadata and controls
31 lines (29 loc) · 1.07 KB
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
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
String source = "source.data";
String dest = "dest.data";
File sour = new File(source),des = new File(dest);
if (!sour.exists()){
sour.createNewFile();
FileOutputStream outputStream = new FileOutputStream(sour);
outputStream.write("nihao".getBytes());
outputStream.close();
}
if (!des.exists()) {
des.createNewFile();
}
FileChannel in = new FileInputStream(source).getChannel(),
out = new FileOutputStream(dest).getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(BSIZE);
//通过-1判断是否到底末尾
while (in.read(byteBuffer) != -1) {
byteBuffer.flip(); //Prepare for writing
out.write(byteBuffer);
byteBuffer.clear(); //Prepare for reading
}
}
}