source: trunk/java-utils/src/main/java/de/ugoe/cs/util/FileTools.java @ 2172

Last change on this file since 2172 was 1451, checked in by sherbold, 11 years ago
  • Property svn:mime-type set to text/plain
File size: 6.1 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.util;
16
17import java.io.BufferedWriter;
18import java.io.File;
19import java.io.FileInputStream;
20import java.io.FileNotFoundException;
21import java.io.FileReader;
22import java.io.FileWriter;
23import java.io.IOException;
24import java.io.InputStreamReader;
25import java.nio.charset.Charset;
26
27/**
28 * <p>
29 * Helper class that provides methods that simplify working with files.
30 * </p>
31 *
32 * @author Steffen Herbold
33 * @version 1.0
34 */
35public class FileTools {
36
37    /**
38     * <p>
39     * Private constructor to prevent initializing of the class.
40     * </p>
41     */
42    private FileTools() {
43
44    }
45
46    /**
47     * <p>
48     * Returns an array of the lines contained in a file. The line separator is
49     * {@link StringTools#ENDLINE}.
50     * </p>
51     *
52     * @param filename
53     *            name of the file
54     * @return string array, where each line contains a file
55     * @throws IOException
56     *             see {@link FileReader#read(char[])}, {@link FileReader#close()}
57     * @throws FileNotFoundException
58     *             see {@link FileReader#FileReader(File)}
59     */
60    public static String[] getLinesFromFile(String filename) throws IOException,
61        FileNotFoundException
62    {
63        boolean carriageReturn = true;
64        if (StringTools.ENDLINE.equals("\n")) {
65            carriageReturn = false;
66        }
67        return getLinesFromFile(filename, carriageReturn);
68    }
69
70    /**
71     * <p>
72     * Returns an array of the lines contained in a file.
73     * </p>
74     *
75     * @param filename
76     *            name of the file
77     * @param carriageReturn
78     *            if true, "\r\n", if false "\n" is used as line separator
79     * @return string array, where each line contains a file
80     * @throws IOException
81     *             see {@link FileReader#read(char[])}, {@link FileReader#close()}
82     * @throws FileNotFoundException
83     *             see {@link FileReader#FileReader(File)}
84     */
85    public static String[] getLinesFromFile(String filename, boolean carriageReturn)
86        throws IOException, FileNotFoundException
87    {
88        File f = new File(filename);
89        FileInputStream fis = new FileInputStream(f);
90        InputStreamReader reader = new InputStreamReader(fis, Charset.defaultCharset());
91        char[] buffer = new char[(int) f.length()];
92        reader.read(buffer);
93        reader.close();
94        String splitString;
95        if (carriageReturn) {
96            splitString = "\r\n";
97        }
98        else {
99            splitString = "\n";
100        }
101        return (new String(buffer)).split(splitString);
102    }
103
104    /**
105     * <p>
106     * Writes an array to a file using the toString function of its object.
107     * </p>
108     *
109     * @param array
110     *            array that is written
111     * @param filename
112     *            name of the output file
113     * @param separator
114     *            separator string that is put between the array objects
115     * @param lineBreak
116     *            if true, a new line is added after each array element and its separator
117     * @throws IOException
118     *             see {@link BufferedWriter#write(String)}, {@link BufferedWriter#newLine()},
119     *             {@link BufferedWriter#flush()}, {@link BufferedWriter#close()},
120     *             {@link FileWriter#FileWriter(String)}
121     */
122    public static <T> void writeArrayToFile(T[] array,
123                                            String filename,
124                                            String separator,
125                                            boolean lineBreak) throws IOException
126    {
127        BufferedWriter outputWriter = null;
128        outputWriter = new BufferedWriter(new FileWriter(filename));
129        for (int i = 0; i < array.length; i++) {
130            outputWriter.write(array[i].toString());
131            if (i < array.length - 1) {
132                outputWriter.write(separator);
133                if (lineBreak) {
134                    outputWriter.newLine();
135                }
136            }
137        }
138        outputWriter.flush();
139        outputWriter.close();
140    }
141
142    /**
143     * <p>
144     * Autocompletes a given path. The path must be absolute. Otherwise, autocompletion is not
145     * possible.
146     * </p>
147     *
148     * @param prefix
149     *            the prefix to be complete
150     * @return the auto completed path
151     */
152    public static String autoCompletePath(String prefix) {
153        File prefixFile = new File(prefix);
154        File parentDir = prefixFile.getParentFile();
155
156        if (parentDir == null) {
157            // the prefix does not denote a path or denotes one of the root directories.
158            // this can not be auto completed
159            return prefix;
160        }
161
162        String[] completions = null;
163
164        if (parentDir.exists()) {
165            completions = parentDir.list();
166        }
167
168        if (completions == null) {
169            completions = new String[0];
170        }
171
172        String completedPrefix;
173
174        completedPrefix = StringTools.autocomplete(prefixFile.getName(), completions);
175
176        File completedFile = new File(parentDir, completedPrefix);
177
178        if (completedFile.exists() && completedFile.isDirectory()) {
179            return completedFile.getAbsolutePath() + File.separator;
180        }
181        else {
182            return (parentDir.getAbsolutePath() + File.separator + completedPrefix)
183                .replaceAll("//", "/");
184        }
185    }
186
187}
Note: See TracBrowser for help on using the repository browser.