Repository navigation
Expand file tree
/
Copy pathOutputWriter.java
More file actions
55 lines (48 loc) · 1.7 KB
/
Copy pathOutputWriter.java
File metadata and controls
55 lines (48 loc) · 1.7 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
package redirect;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class OutputWriter {
public static void write(String text, Redirect redirect) {
if (redirect == null) {
System.out.println(text);
return;
}
switch (redirect.type()) {
case STDOUT -> writeToFile(text, redirect.filePath(), false);
case STDOUT_APPEND -> writeToFile(text, redirect.filePath(), true);
default -> {
System.out.println(text);
createEmptyFile(redirect.filePath());
}
}
}
public static void writeError(String text, Redirect redirect) {
if (redirect == null) {
System.err.println(text);
return;
}
switch (redirect.type()) {
case STDERR -> writeToFile(text, redirect.filePath(), false);
case STDERR_APPEND -> writeToFile(text, redirect.filePath(), true);
default -> {
System.err.println(text);
createEmptyFile(redirect.filePath());
}
}
}
private static void writeToFile(String text, String path, boolean append) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path, append))) {
bw.write(text);
bw.newLine();
} catch (IOException e) {
System.err.printf("error writing to file: %s%n", e.getMessage());
}
}
private static void createEmptyFile(String path) {
try (FileWriter ignored = new FileWriter(path, false)) {
} catch (IOException e) {
System.err.printf("error creating file: %s%n", e.getMessage());
}
}
}