2012-07-30 63 views
0

我有以下内容(分隔符是一个空格)的文本文件:爪哇 - 解析与整数和字符串文本文件

1231 2134 143 wqfdfv -89 rwq f 8 qer q2 
sl;akfj salfj 3 sl 123 

我的目标是读整数和字符串seperately。一旦我知道如何解析它们,我将创建另一个输出文件来保存它们(但我的问题只是知道如何解析这个文本文件)。

我尝试使用扫描仪和我不能够获得超越第一INETGER:

Scanner s = new Scanner (new File ("a.txt")).useDelimiter(""); 
while (s.hasNext()){ 
System.out.print(s.nextInt());} 

和输出

1231 

我怎么也透过这两个线以外的整数?

我的期望outout是:

1231 
2134 
143 
-89 
8 
3 
123 

回答

4

分隔符应该是别的东西像至少一个空格或多个

Scanner s = new Scanner (new File ("a.txt")).useDelimiter("\\s+"); 
while (s.hasNext()) { 
    if (s.hasNextInt()) { // check if next token is an int 
     System.out.print(s.nextInt()); // display the found integer 
    } else { 
     s.next(); // else read the next token 
    } 
} 

,我不得不承认,从gotuskar的解决方案是在这个简单的情况下,最好的一个。

+0

哇..那么工作。谢谢! – user547453 2012-07-30 22:47:56

+1

无法重现。也许你正在使用错误的语言环境?尝试使用s.useLocale(Locale.ENGLISH)设置语言环境;是 - 真的很简单吗?或一些有趣的角色? – 2012-07-30 22:52:51

+0

是的,它工作....我没有包括“\\ s +”作为分隔符。 – user547453 2012-07-30 23:01:19

4

当从文件中读取数据,读取所有的字符串类型。然后使用Integer.parseInt()来分析它是否是数字。如果它抛出异常,那么它是一个字符串,否则它是一个数字。

while (s.hasNext()) { 
    String str = s.next(); 
    try { 
     b = Integer.parseInt(str); 
    } catch (NumberFormatException e) { // only catch specific exception 
     // its a string, do what you need to do with it here 
     continue; 
    } 
    // its a number 
} 
+0

我试图使用Integer.parseInt(),我能够捕获异常,但不知道如何返回继续阅读文件。看到我上面的编辑。 – user547453 2012-07-30 23:04:17

+0

谢谢....我学会了使用'继续' – user547453 2012-08-01 21:13:10