JAVA:如何解析文本文件一行中的整数(由可变数量的空格分隔)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12452622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:56:59  来源:igfitidea点击:

JAVA: How to parse Integer numbers (delimited by a variable number of spaces) in a line of a text file

javaparsingintegerlinetext-files

提问by Bob

I want to parse numbers in a line of a text file line by line. For example, imagine _ as a space

我想逐行解析文本文件一行中的数字。例如,把_想象成一个空格

my text file content looks like:

我的文本文件内容如下:

___34_______45
_12___1000
____4______167
...

I think you got the idea. Each line may have variable number of spaces separating the numbers, meaning there is no pattern at all. The simplest solution could be read char by char and check if it is a number and go like that until the end of the number string and parse it. But there must be some other way. How can I read this in Java automatically so that I can get in a certain datastructure say array

我想你明白了。每行可能有不同数量的空格分隔数字,这意味着根本没有模式。最简单的解决方案可以逐个字符读取并检查它是否是一个数字,然后一直这样直到数字字符串的末尾并解析它。但必须有其他方式。我怎样才能在 Java 中自动读取这个,以便我可以进入某个数据结构,比如数组

[34,45]
[12,1000]
[4,167]

回答by Jonathan Paulson

Use java.util.Scanner. It has the nextInt()method, which does exactly what you want. I think you'll have to put them into an array "by hand".

使用java.util.Scanner. 它有nextInt()方法,它完全符合你的要求。我认为您必须“手动”将它们放入数组中。

import java.util.Scanner;
public class A {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int v1 = in.nextInt(); //34
    int v2 = in.nextInt(); //45
    ...
  }
}

回答by pb2q

If you only need your numbers in a data structure, e.g. a flat array, then you can read the file with a Scannerand a simple loop. Scanneruses whitespace as the default delimiter, skipping multiple whitespaces.

如果您只需要数据结构中的数字,例如平面数组,那么您可以使用 aScanner和一个简单的循环读取文件。Scanner使用空格作为默认分隔符,跳过多个空格。

Given List ints:

鉴于List ints

Scanner scan = new Scanner(file); // or pass an InputStream, String
while (scan.hasNext())
{
    ints.add(scan.nextInt());
    // ...

You'll need to handle exceptions on Scanner.nextInt.

您需要在 上处理异常Scanner.nextInt

But your proposed output data structure uses multiple arrays, one per line. You can read the file using Scanner.nextLine()to get individual lines as String. Then use String.splitto split around whitespaces with a regex:

但是您建议的输出数据结构使用多个数组,每行一个。您可以使用Scanner.nextLine()将单个行读取为String. 然后使用String.split正则表达式来分割空格:

Scanner scan = new Scanner(file); // or InputStream
String line;
String[] strs;    
while (scan.hasNextLine())
{
    line = scan.nextLine();

    // trim so that we get rid of leading whitespace, which will end
    //    up in strs as an empty string
    strs = line.trim().split("\s+");

    // convert strs to ints
}

You could also use a second Scannerto tokenize each individual line in an inner loop. Scannerwill discard any leading whitespace for you, so you can leave off the trim.

您还可以使用秒Scanner来标记内部循环中的每一行。Scanner将为您丢弃任何前导空格,因此您可以省略trim.

回答by Roddy of the Frozen Peas

Bum it old-school with BufferedReaderand String's split()function:

Bum it old school withBufferedReader和 String 的split()功能:

BufferedReader in = null;
try {
    in = new BufferedReader(new FileReader(inputFile));
    String line;
    while ((line = in.readLine()) != null) {
        String[] inputLine = line.split("\s+");
        // do something with your input array
    }
} catch (Exception e) {
    // error logging
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (Exception ignored) {}
    }
}

(If you're using Java 7, the finallyblock is unnecessary if you use the try-with-resources.)

(如果您使用的是 Java 7,finally那么如果您使用 try-with-resources ,则该块是不必要的。)

This will change something like ______45___23(where _ is whitespace) into an array ["45", "23"]. If you need those as integers, it's quite trivial to write a function to convert the String array into an int array:

这会将类似______45___23(其中 _ 是空格)的内容更改为数组["45", "23"]。如果您需要将它们作为整数,编写一个函数将 String 数组转换为一个 int 数组是非常简单的:

public int[] convert(String[] s) {
    int[] out = new int[s.length];
    for (int i=0; i < out.length; i++) {
        out[i] = Integer.parseInt(s[i]);
    }
    return out;
}