-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputReader.java
84 lines (74 loc) · 2.2 KB
/
InputReader.java
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
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* Class for reading input from file. You may want to expand it, if needed...
*
* @author (Per Lauvås & Tor-Morten Grønli)
* @version (2.0)
*/
public class InputReader
{
/**
* Constructor for objects of class InputReader
*/
public InputReader()
{
}
/**
* Return all the words in a file - BufferedReader implementation
*
* @param filename the name of the file
* @return an arraylist of all the words in the file
*/
public ArrayList<String> getWordsInFile(String filename)
{
ArrayList<String> words = new ArrayList<>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename),
"8859_1"));
String line = in.readLine();
while(line != null) {
String [] elements = line.split(" ");
for(int i = 0 ; i < elements.length ; i++){
words.add(elements[i]);
}
line = in.readLine();
}
in.close();
}
catch(IOException exc) {
System.out.println("Error reading words in file: " + exc);
}
return words;
}
/**
* Return all the words in a file - scanner implementation
*
* @param filename the name of the file
* @return an arraylist of all the words in the file
*/
public ArrayList<String> getWordsInFileWithScanner(String filename)
{
ArrayList<String> words = new ArrayList<>();
try{
Scanner in = new Scanner(new FileInputStream(filename));
while(in.hasNext())
{
words.add(in.next());
}
}
catch(IOException exc) {
System.out.println("Error reading words in file: " + exc);
}
return words;
}
}