简体   繁体   English

Java-解析具有整数和字符串的文本文件

[英]Java - Parsing a text file with integers and strings

I have a text file with the following contents (delimiter is a single space): 我有一个包含以下内容的文本文件(定界符为单个空格):

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

My objective is to read the integers and strings seperately. 我的目标是分别读取整数和字符串。 Once I know how to parse them, I will create another output file to save them (but my question is only to know how to parse this text file). 一旦知道如何解析它们,我将创建另一个输出文件以保存它们(但我的问题只是知道如何解析此文本文件)。

I tried using Scanner and I am NOT able to get beyond the first inetger: 我尝试使用Scanner,但无法超越第一个inetger:

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

and the output is 输出是

1231

How can I also get other integers from both the lines? 如何从这两行中获取其他整数?

My desired outout is: 我想要的输出是:

1231 
2134 
143
-89
8
3 
123

When reading data from file, read all as string types. 从文件读取数据时,将所有内容读取为字符串类型。 Then test whether it is number by parsing it using Integer.parseInt() . 然后通过使用Integer.parseInt()进行解析来测试它是否为数字。 If it throws an exception then it is a string, otherwise it is a number. 如果抛出异常,则为字符串,否则为数字。

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
 } 

The delimiter should be something else like at least one whitespace or more 分隔符应该是至少一个或多个空白

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

and i have to admit that the solution from gotuskar is the better one in this simple case. 我必须承认,在这种简单情况下,gotuskar的解决方案是更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM