[英]Java Text Input: How to ignore lines starting with certain characters in them?
我基本上想忽略某些帶有字符的行,就像是否有一行
// 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();
}
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()]);
}
正如Andrew Thompson指出的那樣,最好將文件逐行讀取到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++;
}
}
基本上,您在正確的道路上。
注意 :您可能對startsWith()字符串函數感興趣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.