Reputation: 61
I'm still really new to Java, and I've been at this issue for a while now. I've got a text file like this:
city name,x,y
Beijing
367
661
London
375
625
Washington
802
737
so as the first line states, after each city name there's an x and y value and what I'm trying to do is to read each line of the file and take in the x and y value. Right now I've got a reader method i can use:
public class MyFileReader {
public MyFileReader(String fileName) {
try {
in = new BufferedReader(new FileReader(fileName));
buffer = in.readLine(); // Store first line
}
catch (IOException e) {
System.out.println("Cannot read file \'"+fileName+"\'");
System.exit(0);
}
}}
public String readString() {
String line = buffer;
if (buffer == null) {
System.out.println("Error. The end of file was reached, so another string cannot be read from it");
return null;
}
try {
buffer = in.readLine();
}
catch (IOException e) {
System.out.println("Error. Cannot read from file");
System.exit(0);
}
return line;
}
Here is my current code:
public Program(String filename, Boolean b){
cityArray = new City[3];
//the following line is the line I feel has an issue
MyFileReader filereader = new MyFileReader(filename);
String line;
int i = 0;
while((line=filereader.readString())!=null)
{
String[] ar =line.split("\n");
City arr = new City(ar[0], Integer.parseInt(ar[1]) , Integer.parseInt(ar[2]));
cityArray[i++] = arr;
}
if (b){
Map citymap = new Map();
for (City city : cityArray){
citymap.addCity(city);
}}}
Sorry for the long question, but basically, the MyfileReader can't seem to read the text properly and keeps outputting: "Error. Cannot read from file", which seems to mean IOError. With my limited experience, errors usually point out where in your code you screwed up and sometimes how, but in this case I really have no idea. (I'm eventually supposed to add city name and x and y to cityArray)
Upvotes: 0
Views: 129
Reputation: 912
Your actual 'Cannot read from file' error is happening in this line:
in = new BufferedReader(new FileReader(fileName));
This is most likely because you have not provided a correct path to the file.
Test your code with a full absolute path. Later change your code to use a relative path.
The second problem I see in this line: String[] ar =line.split("\n");
You read one line and then you 'split' it into blocks using 'end-of-line character' as a separator. I assume it should be ' ' (space), if you have one city per line.
Upvotes: 1