forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileChannelWrite.java
More file actions
41 lines (30 loc) · 1.22 KB
/
FileChannelWrite.java
File metadata and controls
41 lines (30 loc) · 1.22 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
package com.zetcode;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class FileChannelWrite {
public static void main(String[] args) throws IOException {
var fileName = "src/resources/thermopylae.txt";
var myfile = new RandomAccessFile(fileName, "rw");
try (var fileChannel = myfile.getChannel()) {
var text = getText();
byte[] byteData = text.getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.wrap(byteData);
fileChannel.write(buffer);
}
}
private static String getText() {
var lineSeparator = System.getProperty("line.separator");
var sb = new StringBuilder();
sb.append("The Battle of Thermopylae was fought between " +
"an alliance of Greek city-states,");
sb.append(lineSeparator);
sb.append("led by King Leonidas of Sparta, and " +
"the Persian Empire of Xerxes I over the");
sb.append(lineSeparator);
sb.append("course of three days, during the " +
"second Persian invasion of Greece.");
return sb.toString();
}
}