forked from coderbruis/JavaSourceCodeLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMappedByteBufferTest.java
More file actions
74 lines (64 loc) · 2.17 KB
/
Copy pathMappedByteBufferTest.java
File metadata and controls
74 lines (64 loc) · 2.17 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.learnjava.io.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author LuoHaiYang
*/
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt", "rw");
// get channel
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0, (byte) 'H');
mappedByteBuffer.put(3, (byte) '9');
// IndexOutOfBoundsException
mappedByteBuffer.put(5, (byte) 'Y');
randomAccessFile.close();
System.out.println("change success");
}
/**
*
* @param from
* @param to
* @throws IOException
*/
public static void mmap4zeroCopy(String from, String to) throws IOException {
FileChannel source = null;
FileChannel destination = null;
try {
source = new RandomAccessFile(from, "r").getChannel();
destination = new RandomAccessFile(to, "rw").getChannel();
MappedByteBuffer inMappedBuf =
source.map(FileChannel.MapMode.READ_ONLY, 0, source.size());
destination.write(inMappedBuf);
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
public static void sendfile4zeroCopy(String from, String to) throws IOException{
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(from).getChannel();
destination = new FileOutputStream(to).getChannel();
source.transferTo(0, source.size(), destination);
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}