-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNIOHelper.java
More file actions
71 lines (64 loc) · 2.11 KB
/
Copy pathNIOHelper.java
File metadata and controls
71 lines (64 loc) · 2.11 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
package io.NIO;
import io.Content;
import io.Helper;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOHelper extends Content implements Helper {
public String read() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
RandomAccessFile accessFile = null;
StringBuilder stringBuilder = new StringBuilder();
try {
accessFile = new RandomAccessFile(DIR, "rw");
FileChannel inChannel = accessFile.getChannel();
int bytesRead = 0;
bytesRead = inChannel.read(buffer);
while (bytesRead != -1) {
System.out.println("bytesRead: " + bytesRead);
buffer.flip();
while (buffer.hasRemaining()) {
stringBuilder.append((char) buffer.get());
}
buffer.clear();
bytesRead = inChannel.read(buffer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
accessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
public void write(String str) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
FileOutputStream accessFile = null;
try {
accessFile = new FileOutputStream(DIR, true);
FileChannel inChannel = accessFile.getChannel();
str += "\n";
buffer.put(str.getBytes());
buffer.flip();
inChannel.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
accessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}