读取文件中的特定信息

时间:2015-11-17 15:47:53

标签: java file

我想使用Scanner读取此文件,但不是所有信息,只有分数后的内容,如10,warrior,John Smith等。

currhp: 10

type: Warrior

name: John Smith

items:
      Stick,1,2,10,5

gold: 10

type: Wizard

我试图解决它,但我无法解决。

Scanner infile;

Scanner inp = new Scanner(System.in);

try {

 infile =    new Scanner(new File("player_save.txt"));

} catch    (FileNotFoundException o) {

 System.out.println(o); return; }

while (infile.hasNextLine()) { 

System.out.println(infile.nextLine()); 

}

2 个答案:

答案 0 :(得分:2)

您需要打开文件,逐行读取然后拆分每一行并使用您希望对其进行进一步处理的行的块。

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

public class ReadFile{
    public static void main(String[] args) throws IOException {
        //fix the URL to where your file is located.
        try (BufferedReader br = new BufferedReader(new FileReader("C:\\player_save.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.length() > 0) {
                      if(line.contains(":")) {
                          System.out.println("Before colon >> " + line.split(":")[0]);  
                       } else {
                          //no column found taking the whole line
                         System.out.println("whole line having no coln: " + line);                    
                     }
                }
            }
        } catch(FileNotFoundException fnfe) {   
          //Handle scenario where the file does not exist   
        } catch(IOException ie) {
          //Handle other File I/O exceptions here
        }
    }
}

答案 1 :(得分:0)

你可以这样做 -

List<String> list= new ArrayList<>();
    try(
    Scanner scan= new Scanner(new BufferedReader(new FileReader("//your filepath")));
    ){      

    while(scan.hasNextLine()){
        String s=scan.nextLine();
        if(s.contains(":")){
            String arr[]=s.split(":");
            list.add(arr[1].trim());
            }
        }
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
    for(String str:list){
        System.out.println(str);
    }