Debian Codegraph @

util/buildscripts/webbuild/server/src/org/dtk/FileUtil.java

raw symbols SCIP
1 package org.dtk;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.io.OutputStreamWriter;
12 import java.util.zip.GZIPOutputStream;
13
14 public class FileUtil {
15
16 public static String readFromFile(String path, String encoding) throws IOException {
17 // summary: reads a file and returns a string
18 if (encoding == null) {
19 encoding = "utf-8";
20 }
21 File file = new File(path);
22 String lineSeparator = System.getProperty("line.separator");
23 BufferedReader input = new java.io.BufferedReader(
24 new InputStreamReader(new FileInputStream(file), encoding));
25 try {
26 StringBuffer stringBuffer = new StringBuffer();
27 String line = input.readLine();
28
29 // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page
30 // 324
31 // http://www.unicode.org/faq/utf_bom.html
32
33 // Note that when we use utf-8, the BOM should appear as "EF BB BF",
34 // but it doesn't due to this bug in the JDK:
35 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
36 if (line != null && line.length() > 0 && line.charAt(0) == 0xfeff) {
37 // Eat the BOM, since we've already found the encoding on this
38 // file,
39 // and we plan to concatenating this buffer with others; the BOM
40 // should
41 // only appear at the top of a file.
42 line = line.substring(1);
43 }
44 while (line != null) {
45 stringBuffer.append(line);
46 stringBuffer.append(lineSeparator);
47 line = input.readLine();
48 }
49 // Make sure we return a JavaScript string and not a Java string.
50 return stringBuffer.toString(); // String
51 } finally {
52 input.close();
53 }
54 }
55
56 public static void writeToFile(String path, String contents, String encoding, boolean useGzip) throws IOException {
57 // summary: writes a file
58 if (encoding == null) {
59 encoding = "utf-8";
60 }
61 File file = new File(path);
62
63 //Make sure destination dir exists.
64 File parentDir = file.getParentFile();
65 if(!parentDir.exists()){
66 if(!parentDir.mkdirs()){
67 throw new IOException("Could not create directory: " + parentDir.getAbsolutePath());
68 }
69 }
70
71 OutputStream outStream = new FileOutputStream(file);
72 if (useGzip) {
73 outStream = new GZIPOutputStream(outStream);
74 } else {
75
76 }
77
78 BufferedWriter output = new java.io.BufferedWriter(new OutputStreamWriter(outStream, encoding));
79 try {
80 output.append(contents);
81 } finally {
82 output.close();
83 }
84
85 }
86 }