Java Text Input: Как игнорировать строки, начинающиеся с определенных символов в них?
Я в основном хочу игнорировать определенные строки с символами в них, например, если есть строка
// hello, i'm bill
Я хочу игнорировать эту строку при чтении, потому что она содержит символ "//". Как я могу это сделать? Я попробовал метод skip(), но он дает мне ошибки.
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;
}
Обновление: ЗДЕСЬ МОЙ ОСНОВНОЙ МЕТОД:
try{
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
}
2 ответа
Решение
while ((line = textReader.readLine()) != null) {
// I tried this:
if (line.contains("//")) {
continue;
}
numberOfLines++;
}
Обратите внимание, что continue
может показаться немного странным и склонным к критике
отредактируйте вот что вам нужно (обратите внимание, что для этого не нужен метод countLines)
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()]);
}
Как указывает Эндрю Томпсон, было бы лучше прочитать файл построчно в ArrayList. Псевдо-код:
For Each Line In File
If LineIsValid()
AddLineToArrayList()
Next
ОБНОВЛЕНИЕ, чтобы исправить ваш фактический код:
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int BufferIndex = 0;
String line;
while ((line = textReader.readLine()) != null) {
if (line.trim().startsWith("//")) {
// Don't inject current line into buffer
}else{
textData[BufferIndex] = textReader.readLine();
BufferIndex = BufferIndex + 1;
}
}
// close the line-by-line reader and return the data
textReader.close();
return textData;
}
В вашей функции ReadLines():
while ((line = textReader.readLine()) != null) {
if (line.trim().startsWith("//")) {
// do nothing
}else{
numberOfLines++;
}
}
По сути, вы на правильном пути.
Примечание: вас может заинтересовать строковая функция StartWith()