-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileReader.java
More file actions
93 lines (76 loc) · 2.06 KB
/
Copy pathFileReader.java
File metadata and controls
93 lines (76 loc) · 2.06 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
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/*
* Reads data from a file
*/
public class FileReader {
private Scanner fileReader; // The Scanner object to read the file
private File myFile; // The File object containing the data
/*
* Constructor to create a FileReader with
* the specified filename to read
*/
public FileReader(String filename) {
setFile(filename);
}
/*
* Sets the file to the specified filename
*/
public void setFile(String filename) {
myFile = new File(filename);
fileReader = createScanner(myFile);
}
/*
* Returns a Scanner object to read the file
* or notifies the user if the file is not found
*/
public Scanner createScanner(File theFile) {
Scanner tempScanner = null;
try {
tempScanner = new Scanner(theFile);
} catch(FileNotFoundException error) {
System.out.println("File not found.");
}
return tempScanner;
}
/*
* Returns an int array containing the values in the file
*/
public int[] getIntData(int numValues) {
int[] values = new int[numValues];
for (int index = 0; index < values.length; index++) {
if (fileReader.hasNextInt()) {
values[index] = fileReader.nextInt();
}
}
fileReader.close();
return values;
}
/*
* Returns a double array containing the values in the file
*/
public double[] getDoubleData(int numValues) {
double[] values = new double[numValues];
for (int index = 0; index < values.length; index++) {
if (fileReader.hasNextDouble()) {
values[index] = fileReader.nextDouble();
}
}
fileReader.close();
return values;
}
/*
* Returns a String array containing the values in the file
*/
public String[] getStringData(int numValues) {
String[] values = new String[numValues];
for (int index = 0; index < values.length; index++) {
if (fileReader.hasNextLine()) {
values[index] = fileReader.nextLine();
}
}
fileReader.close();
return values;
}
}