簡體   English   中英

在Java中讀取文件時忽略一行

[英]Ignore a line while reading a file in java

我有一些代碼可以從文件中讀取行,我想識別行何時開始或fisrt字符(非空白)為' * '並忽略它,因此在while語句中添加如下內容

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

我有類似的東西:

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

如何完成代碼?

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

將while循環更改為:

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

編輯

如果“ *”不是在行的開頭而是在行的某個位置,請使用以下命令

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

其中position可以是一個整數,指定您感興趣的位置。

假定帶有*標記和行尾注釋,此循環將保留行中任何需要的內容。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM