java读取txt并获取某一部分字符串

比如我的txt内容是
test1---aa
test2---bb
test3---cc
请问我如何能拿到bb?

例如现在E盘下有个txt文件,bb.txt
里面的内容是:
test1---aa
test2---bb
test3---cc
那么你可以一次读取一行,然后对单独对每行进行处理
例如代码:

File file = new File("E:\\bb.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine())!= null){ //一次读取一行
System.out.println(line);
String[] tmp = line.split("--"); //根据--将每行数据拆分成一个数组
for(int i=0; i<tmp.length; i++){
System.out.println("\t" + tmp[i]); //tmp[1]就是你想要的bb
}
}
br.close();追问

事实上我不知道哪一行是bb,所以tmp[1]不行吧

追答

File file = new File("E:\\bb.txt");

BufferedReader br = new BufferedReader(new FileReader(file));

String line = null;

while((line = br.readLine())!= null){ //一次读取一行

System.out.println(line);

String[] tmp = line.split("---"); //根据--将每行数据拆分成一个数组

for(int i=0; i<tmp.length; i++){

System.out.println("\t" + tmp[i]); //tmp[1]就是你想要的bb

}

if(line.endsWith("bb")){

    //判断本行是否以bb结束

System.out.println("这是我想要的: " + tmp[1]);

}

}

br.close();


温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-09-03
用FileReader一行行读进来。每次读一行检查下string是否包含bb。
第2个回答  2014-09-03

 public static String readFile(String filepath) {
  StringBuffer string=new StringBuffer();
  BufferedReader br=null;
  try {
   InputStreamReader isr = new InputStreamReader(new FileInputStream(filepath));
   br=new BufferedReader(isr);    
   String line = null;       
   while((line=br.readLine())!= null){  
    string.append(line);
    string.append("\n");
    }   
    br.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return string.toString();
 }

 

 public static String rightStr(String str, int count) {
  String result = "";
  if (!strIsNull(str)) {
   if (str.length() > count) {
    result = str.substring(str.length() - count);
   } else {
    result = str;
   }
  }
  return result;
 }

给两个方法你参考下

相似回答