forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileOutputStreamExampleTest.java
More file actions
49 lines (43 loc) · 1.43 KB
/
FileOutputStreamExampleTest.java
File metadata and controls
49 lines (43 loc) · 1.43 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
package com.examplehub.basics.io;
import static org.junit.jupiter.api.Assertions.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
class FileOutputStreamExampleTest {
@Test
void testWriteByteToFile() throws IOException {
try (OutputStream outputStream = new FileOutputStream("temp.txt")) {
outputStream.write('H');
outputStream.write('e');
outputStream.write('l');
outputStream.write('l');
outputStream.write('o');
outputStream.flush();
assertTrue(new File("temp.txt").delete());
}
}
@Test
void testWriteString() throws IOException {
try (OutputStream outputStream = new FileOutputStream("temp.txt")) {
outputStream.write("Hello".getBytes(StandardCharsets.UTF_8));
assertTrue(new File("temp.txt").delete());
}
}
@Test
void testCopyFile() throws IOException {
String srcPath = "pom.xml";
String destPath = "pom.xml.bk";
try (InputStream inputStream = new FileInputStream(srcPath);
OutputStream outputStream = new FileOutputStream(destPath)) {
byte[] bytes = new byte[1024];
int readBytes;
while ((readBytes = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, readBytes);
}
assertEquals(new File(srcPath).length(), new File(destPath).length());
}
Files.deleteIfExists(Paths.get(destPath));
}
}