如何根据java中的条件从文件中获取一行 [英] How can I get a line from a file based on a condtion in java

查看:159
本文介绍了如何根据java中的条件从文件中获取一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我正在逐行阅读。例如

 

  package  com.java2novice.files; 

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadLinesFromFile {

public static void main( String a []){
BufferedReader br = null;
字符串 strLine = ;
尝试 {
br = new BufferedReader( new FileReader( fileName));
while ((strLine = br.readLine())!= null){
System.out.println(strLine);
}
} catch (FileNotFoundException e){
System.err.println( 无法找到文件:fileName);
} catch (IOException e){
System.err.println( 无法读取文件:fileName);
}
}
}





我想从文件中提取一行,如果该行包含Lets C ++。

即如果一行包含Lets C ++,则将整行存储在一个字符串中。

任何人都可以帮我解决这个问题。



提前致谢

解决方案

参见 String.contains(Java Platform SE 7) [ ^ ] 。


你需要的是下面的改变



  while ((strLine = br.readLine())!=  null ){
System。 .println(strLine中);
}





TO



< pre lang =C#> while ((strLine = br.readLine())!= null ) {
if (strLine.toLowerCase()。contains( 让C ++ .toLowerCase())
{
System。 out .println(strLine);
}
}


Hi , I have a file which i am reading line by line.for e.g

package com.java2novice.files;
 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadLinesFromFile {
 
    public static void main(String a[]){
        BufferedReader br = null;
        String strLine = "";
        try {
            br = new BufferedReader( new FileReader("fileName"));
            while( (strLine = br.readLine()) != null){
                System.out.println(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }
    }
}



I want to extract a single line from the file , if the line contains "Lets C++".
i.e if a line contains "Lets C++", store the entire line in a string.
Can anyone help me in getting this.

Thanks in advance

解决方案

See String.contains (Java Platform SE 7 )[^].


What you need is change below

while( (strLine = br.readLine()) != null){
               System.out.println(strLine);
           }



TO

while( (strLine = br.readLine()) != null){
              if( strLine.toLowerCase().contains("Lets C++".toLowerCase())
             {
                  System.out.println(strLine);
             }
          }


这篇关于如何根据java中的条件从文件中获取一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆