1
+ /*
2
+ * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package com .github .pedrovgs .txtToList ;
18
+
19
+ import java .io .BufferedReader ;
20
+ import java .io .FileReader ;
21
+ import java .util .List ;
22
+ import java .util .ArrayList ;
23
+ import java .io .IOException ;
24
+ import java .nio .file .Paths ;
25
+
26
+ /**
27
+ * This class contains and algorithm that reads txt files and turns them to Lists for further use.
28
+ * @author ShoeMaker
29
+ *
30
+ */
31
+
32
+ public class TxtToList {
33
+
34
+ /**
35
+ * Method gets a txt file's path. It opens the file and reads it,
36
+ * then tries to get the txt lines and return them as a List.
37
+ * @param filepath The file's path.
38
+ * @return An List with the file's lines.
39
+ * @throws IllegalArgumentException when an IOException occurs or the file is empty.
40
+ */
41
+
42
+ public List <String > readFileToList (String filepath ) {
43
+
44
+ filepath = Paths .get ("." ).toAbsolutePath ().normalize ().toString () + filepath ;
45
+ List <String > datas = new ArrayList <String >();
46
+ BufferedReader br = null ;
47
+ String line = null ;
48
+ try {
49
+ br = new BufferedReader (new FileReader (filepath ));
50
+ line = br .readLine ();
51
+ while (line != null ) {
52
+
53
+ if (line != null ) {
54
+ datas .add (line );
55
+ }
56
+ line = br .readLine ();
57
+ }
58
+
59
+ br .close ();
60
+ } catch (IOException e ) {
61
+ throw new IllegalArgumentException ("Something went wrong while reading the file. Probably wrong path or file doesn't exist." );
62
+ }
63
+ if (datas .size () == 0 ) {
64
+ throw new IllegalArgumentException ("File was empty." );
65
+ }
66
+
67
+ return datas ;
68
+ }
69
+ }
0 commit comments