forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomAccessFileExampleTest.java
More file actions
32 lines (28 loc) · 1.06 KB
/
RandomAccessFileExampleTest.java
File metadata and controls
32 lines (28 loc) · 1.06 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
package com.examplehub.basics.io;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
class RandomAccessFileExampleTest {
@Test
void testSeek() throws IOException {
String filename = "example.txt";
try (PrintStream printStream = new PrintStream(new FileOutputStream(filename));
RandomAccessFile randomAccessFile = new RandomAccessFile(filename, "rw")) {
printStream.write("Java".getBytes(StandardCharsets.UTF_8));
printStream.flush();
assertEquals('J', randomAccessFile.read());
randomAccessFile.seek(2);
assertEquals('v', randomAccessFile.read());
randomAccessFile.write("123".getBytes(StandardCharsets.UTF_8));
randomAccessFile.seek(0);
assertEquals("Jav123", randomAccessFile.readLine());
}
assertTrue(Files.deleteIfExists(Paths.get(filename)));
}
}