I basically want to ignore certain lines with characters in them, like if there's a line
// hello, i'm bill
I want to ignore that line while reading it because it contains the character "//". How can I do that? I tried method skip(), but it gives me errors.
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i<numberOfLines; i++) {
textData[i] = textReader.readLine();
}
// close the line-by-line reader and return the data
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
String line;
int numberOfLines = 0;
while ((line = textReader.readLine()) != null) {
// I tried this:
if (line.contains("//")) {
line.skip();
}
numberOfLines++;
}
reader.close();
return numberOfLines;
}
Update: HERE's MY MAIN METHOD:
try{
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
}
while ((line = textReader.readLine()) != null) {
// I tried this:
if (line.contains("//")) {
continue;
}
numberOfLines++;
}
note that continue
might seem a bit goto like and be prone to critique
edit here's what you are after (note this doesn't need the countLines method)
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
List<String> textData = new LinkedList<String>();//linked list to avoid realloc
String line;
while ((line = textReader.readLine()) != null) {
if (!line.contains("//")) textData.add(line);
}
// close the line-by-line reader and return the data
textReader.close();
return textData.toArray(new String[textData.size()]);
}