| 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 |
|
| 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 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
if (line != null && line.length() > 0 && line.charAt(0) == 0xfeff) { |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
line = line.substring(1); |
| 43 |
} |
| 44 |
while (line != null) { |
| 45 |
stringBuffer.append(line); |
| 46 |
stringBuffer.append(lineSeparator); |
| 47 |
line = input.readLine(); |
| 48 |
} |
| 49 |
|
| 50 |
return stringBuffer.toString(); |
| 51 |
} finally { |
| 52 |
input.close(); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
public static void writeToFile(String path, String contents, String encoding, boolean useGzip) throws IOException { |
| 57 |
|
| 58 |
if (encoding == null) { |
| 59 |
encoding = "utf-8"; |
| 60 |
} |
| 61 |
File file = new File(path); |
| 62 |
|
| 63 |
|
| 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 |
} |