1 | package de.ugoe.cs.util;
|
---|
2 |
|
---|
3 | import java.io.File;
|
---|
4 | import java.io.FileNotFoundException;
|
---|
5 | import java.io.FileReader;
|
---|
6 | import 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 | */
|
---|
16 | public 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 | }
|
---|