]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.runtime/src/org/simantics/scl/runtime/procedure/StringIO.java
Added StringIO.readContentsWithCharset
[simantics/platform.git] / bundles / org.simantics.scl.runtime / src / org / simantics / scl / runtime / procedure / StringIO.java
1 package org.simantics.scl.runtime.procedure;
2
3 import java.io.BufferedWriter;
4 import java.io.IOException;
5 import java.nio.charset.Charset;
6 import java.nio.charset.MalformedInputException;
7 import java.nio.file.Files;
8 import java.nio.file.Paths;
9 import java.nio.file.StandardOpenOption;
10 import java.util.List;
11
12 public class StringIO {
13     public static final Charset UTF8 = Charset.forName("UTF-8"); 
14     
15     public static List<String> readLines(String fileName) throws IOException {
16         try {
17             return Files.readAllLines(Paths.get(fileName), UTF8);
18         } catch(MalformedInputException e) {
19             throw new RuntimeException("Encoding of the file '" + fileName + "' does not conform to UTF-8 (without BOM).");
20         }
21     }
22     
23     public static List<String> readLinesWithCharset(String charset, String fileName) throws IOException {
24         try {
25             return Files.readAllLines(Paths.get(fileName), Charset.forName(charset));
26         } catch(MalformedInputException e) {
27             throw new RuntimeException("Encoding of the file '" + fileName + "' does not conform to " + charset + ".");
28         }
29     }
30
31     public static String readContentsWithCharset(String charset, String fileName) throws IOException {
32         try {
33             Charset cs = Charset.forName(charset);
34             return new String(Files.readAllBytes(Paths.get(fileName)), cs);
35         } catch(MalformedInputException e) {
36             throw new RuntimeException("Encoding of the file '" + fileName + "' does not conform to " + charset + ".");
37         }
38     }
39
40     public static void writeLines(String fileName, List<String> lines) throws IOException {
41         BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName), UTF8);
42         for(String line : lines) {
43             writer.write(line);
44             writer.write("\n");
45         }
46         writer.close();
47     }
48     
49     public static void appendLine(String fileName, String line) throws IOException {
50         BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName), UTF8,
51                 StandardOpenOption.CREATE, StandardOpenOption.APPEND);
52         writer.write(line);
53         writer.write("\n");
54         writer.close();
55     }
56
57 }