1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.javagen.agile.core.util;
17
18 import java.io.BufferedReader;
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.util.ArrayList;
25 import java.util.List;
26
27 public class FileUtil
28 {
29
30 public static final String CRLF = System.getProperties().getProperty("line.separator");
31 public static final String EOF = new String(new char[] { 0x1A });
32
33 private FileUtil() { }
34
35 public static void writeStringAsFile(String text, File outputFile) throws IOException {
36 createDir(outputFile);
37 FileOutputStream out = new FileOutputStream(outputFile);
38 out.write(text.getBytes());
39 out.close();
40 }
41
42 public static StringBuilder getInputFileAsString(File inputFile, boolean trimLines) throws IOException
43 {
44 if (!inputFile.exists())
45 return null;
46 StringBuilder fileString = new StringBuilder();
47 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
48 int numLines = 0;
49 String line = readLine(in);
50 while (line != null && !line.equals(EOF)) {
51 if (numLines > 0)
52 fileString.append(CRLF);
53 fileString.append(line);
54 ++numLines;
55 line = readLine(in);
56 }
57 in.close();
58 return fileString;
59 }
60
61 public static List<String> getInputFileAsArray(File inputFile, boolean trimLines) throws IOException
62 {
63 if (!inputFile.exists())
64 return null;
65 List<String> list = new ArrayList<String>();
66 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
67 String line = readLine(in);
68 while (line != null && !line.equals(EOF)) {
69 list.add(line);
70 line = readLine(in);
71 }
72 in.close();
73 return list;
74 }
75
76 /***
77 * Read lines, skipping empty lines and comments (lines that start with '#').
78 *
79 * @param in BufferedReader
80 * @return first non-commented line or null if eof found.
81 * @throws IOException
82 */
83 private static String readLine(BufferedReader in) throws IOException
84 {
85 String line = null;
86 do {
87 line = in.readLine();
88 if (line == null || EOF.equals(line)) {
89 return null;
90 } else {
91 line = line.trim();
92 if (line.length() > 0 && !line.startsWith("#"))
93 return line;
94 }
95 } while (line != null);
96 return line;
97 }
98
99 public static void createDir(File inFile)
100 {
101 if (inFile.exists())
102 return;
103 File parentDir = inFile.getParentFile();
104 if (parentDir!=null) {
105 parentDir.mkdirs();
106 }
107 }
108
109
110 }