2015-11-17 58 views
0

我想用Scanner来阅读这个文件,但不是所有的信息,只有分号后的东西像10,战士,约翰史密斯等等。阅读文件中的具体信息

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

} 
+0

你能给有关该问题的更多细节?你有错误信息吗?你的问题如何与Javascript相关? – Bfcm

+0

因为我想把这些信息放在一个类中,所以我想读取这个文件中的信息,但没有在这个符号后加上字符串:“” without(currhp:,type:,name:,items:,gold:,type:稍后再使用它们。 我希望这个想法已经达到你。 – afafe

回答

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 
     } 
    } 
} 
+0

+1,添加.contains(“:”)验证。可能还有其他的情况,但他的问题并不清楚。你的意思是更新仍然失败? – Raf

+1

您编辑了您的问题,但忘记添加line.contains(“:”)或其他任何事项。但现在你有。好工作 – Neijwiert

+0

干杯,因为你删除了你的+1我反正会给你另一个指向java.lang.ArrayIndexOutOfBoundsException :) – Raf

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