java 在java中读取文件时忽略一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5400582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:56:48  来源:igfitidea点击:

Ignore a line while reading a file in java

java

提问by cMinor

I have some code to read the lines from a file, I would like to recognize when the line starts or the fisrt character (not blank) is '*' and ignore it, so inside the while statement add something like

我有一些代码可以从文件中读取行,我想识别该行何时开始或第一个字符(非空白)是 ' *' 并忽略它,因此在 while 语句中添加类似

if(line[0]=='*') 
   ignore that line

I have something like:

我有类似的东西:

   input = new BufferedReader(new FileReader(new File(finaName)));
    String line = null;
    while ((line = input.readLine()) != null) {
    String[] words = line.split(" "); 
        .... 
    }

How to complete the code?

如何完成代码?

回答by David Weiser

input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
while ((line = input.readLine()) != null) {
  if(line.trim().indexOf('*') == 0)
    continue;
  String[] words = line.split(" "); 
    .... 
}

回答by Suresh Kumar

Change your while loop as:

将您的 while 循环更改为:

while((line = input.readLine()) != null){
   if(!line.startsWith("*")){
      String[] words = line.split(" ");
      ....
   }
}

EDIT

编辑

If "*" is not in the beginning of the line but at some position in the line, use the following

如果“*”不在行首而是在行中的某个位置,请使用以下内容

if(line.indexOf("*") == position){
   ......
}

where position can be an integer specifying the position you are interested in.

其中 position 可以是一个整数,指定您感兴趣的位置。

回答by kieve

Assuming the * marks and end of line comment, this loop will keep anything needed on the line before it.

假设有 * 标记和行尾注释,这个循环会在它之前的行中保留任何需要的东西。

    input = new BufferedReader(new FileReader(new File(finaName)));
    String line = null;
    char[] lineChars;
    while ((line = input.readLine()) != null) {
        lineChars = line.toCharArray();
        line = "";
        for(char c: lineChars){
            if(c == '*')break;
            line.concat(Character.toString(c));
        }
        if(!line.equals(""))
        String[] words = line.split(" ");           
    }