Java文本输入: How to ignore lines starting with certain characters in them?

标签 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;
}

更新:这是我的主要方法:

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

最佳答案

while ((line = textReader.readLine()) != null) {

    // I tried this:
    if (line.contains("//")) {
      continue;
    }

    numberOfLines++;

}

请注意,继续可能看起来有点像 goto 并且容易受到批评

<小时/>

编辑这就是您想要的内容(注意这不需要 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()]);
}

关于Java文本输入: How to ignore lines starting with certain characters in them?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6091736/

相关文章:

java - Google Maps Android api v2 折线长度

java - 如何从高程栅格近似 vector 等高线?

linux - 在日志文件中保留 60 行

C 程序错误地读取文件

javascript - readFileSync 不适用于我。将输入设置为字符串后,我尝试打印输入,但很奇怪

PHP readfile 添加内容长度到输出

java - 如何将两种不同类型的字符串格式解析为日期?

java - 创建和运行 .jar 文件时出现问题

java - 试图让文本文件的每一行成为一个数组列表

java - Java中删除字符串中的重复行