source: trunk/JavaHelperLib/src/de/ugoe/cs/util/FileTools.java @ 175

Last change on this file since 175 was 175, checked in by sherbold, 13 years ago
  • code documentation and formatting
  • Property svn:mime-type set to text/plain
File size: 1.9 KB
Line 
1package de.ugoe.cs.util;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.io.FileReader;
6import java.io.IOException;
7
8/**
9 * <p>
10 * Helper class that provides methods that simplify working with files.
11 * </p>
12 *
13 * @author Steffen Herbold
14 * @version 1.0
15 */
16public class FileTools {
17
18        /**
19         * <p>
20         * Returns an array of the lines contained in a file. The line separator is
21         * "\r\n".
22         * </p>
23         *
24         * @param filename
25         *            name of the file
26         * @return string array, where each line contains a file
27         * @throws IOException
28         *             see {@link FileReader#read(char[])},
29         *             {@link FileReader#close()}
30         * @throws FileNotFoundException
31         *             see {@link FileReader#FileReader(File)}
32         */
33        public static String[] getLinesFromFile(String filename)
34                        throws IOException, FileNotFoundException {
35                return getLinesFromFile(filename, true);
36        }
37
38        /**
39         * <p>
40         * Returns an array of the lines contained in a file.
41         * </p>
42         *
43         * @param filename
44         *            name of the file
45         * @param carriageReturn
46         *            if true, "\r\n", if false "\n" is used as line separator
47         * @return string array, where each line contains a file
48         * @throws IOException
49         *             see {@link FileReader#read(char[])},
50         *             {@link FileReader#close()}
51         * @throws FileNotFoundException
52         *             see {@link FileReader#FileReader(File)}
53         */
54        public static String[] getLinesFromFile(String filename,
55                        boolean carriageReturn) throws IOException, FileNotFoundException {
56                File f = new File(filename);
57                FileReader reader = new FileReader(f);
58                char[] buffer = new char[(int) f.length()];
59                reader.read(buffer);
60                reader.close();
61                String splitString;
62                if (carriageReturn) {
63                        splitString = "\r\n";
64                } else {
65                        splitString = "\n";
66                }
67                return (new String(buffer)).split(splitString);
68        }
69
70}
Note: See TracBrowser for help on using the repository browser.