Java文本输入:如何忽略以某些字符开头的行?

时间:2011-05-23 00:24:53

标签: java lines readfile textreader

我基本上想要忽略某些带有字符的行,比如有一行

// 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;
}

更新:HERE的主要方法:

try{
 ReadFile files = new ReadFile(file.getPath());
 String[] anyLines = files.OpenFile();
 }

2 个答案:

答案 0 :(得分:5)

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()]);
}

答案 1 :(得分:4)

正如Andrew Thompson所指出的那样,最好将文件逐行读入ArrayList。 Pseudo-Code:

 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() string function

感兴趣