-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileParser.java
More file actions
97 lines (91 loc) · 2.51 KB
/
FileParser.java
File metadata and controls
97 lines (91 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.*;
import java.io.*;
/**
* Parse a text file into arrays of words and definitions.
*/
public class FileParser {
String filename;
String [] words;
String [] definitions;
boolean error;
/**
* Constructor.
* @param A valid filename or path+filename.
*/
public FileParser (String filename) {
this.filename=filename;
this.error=false;
}
/**
* Get array of words and phrases.
* @return Array of words or phrases in same order as definitions.
* @see #getDefinitions
*/
public String [] getWords () {
if (words==null) {
loadArrays();
}
return words;
}
/**
* Get array of definitions.
* @return Array of sentences in same order as words.
* @see #getWords
*/
public String [] getDefinitions () {
if (definitions==null) {
loadArrays();
}
return definitions;
}
/**
* Was there an I/O error?
* @return true if there was a problem reading the file.
*/
public boolean error () {
return this.error;
}
int countLines () {
int lines = 0;
try {
File handle = new File(filename);
Scanner scanner = new Scanner(handle);
while (scanner.hasNextLine()) {
scanner.nextLine();
lines++;
}
} catch (Exception e) {
System.err.println("Cannot open file "+filename);
System.err.println(e);
this.error=true;
}
return lines;
}
void loadArrays () {
int lines = countLines();
words = new String [lines];
definitions = new String [lines];
try {
File handle = new File(filename);
Scanner scanner = new Scanner(handle);
int line = 0;
String oneLine;
while (scanner.hasNextLine()) {
oneLine = scanner.nextLine();
String[] split = oneLine.split("\t");
if (split.length==2) {
words[line]=split[0];
definitions[line]=split[1];
line++;
} else {
System.err.println("Cannot parse this text: "+oneLine);
this.error=true;
}
}
} catch (Exception e) {
System.err.println("Cannot open file "+filename);
System.err.println(e);
this.error=true;
}
}
}