简体   繁体   English

Java BufferReader 到按行存储的数组

[英]Java BufferReader To array stored by lines

Given a list of polynoms I need to store them on different arrays depending on the row.给定一个多项式列表,我需要根据行将它们存储在不同的数组中。 Example:例子:

5 -4 2 0 -2 3 0 3 -17 int[] a = {-17, 3, 0, 3, -2, 0, 2, -4, 5} 5 -4 2 0 -2 3 0 3 -17 int[] a = {-17, 3, 0, 3, -2, 0, 2, -4, 5}

4 -2 0 1 int[] b = {1, 0, -2, 4} 4 -2 0 1 int[] b = {1, 0, -2, 4}

First line I need to put on the array a[], and the second one on array b[] Tried something like this:第一行我需要放在数组 a[] 上,第二行放在数组 b[] 上尝试过这样的事情:

File file=new File("Pol.txt");
BufferedReader b=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Pattern delimiters=Pattern.compile(System.getProperty("line.separator")+"|\\s");
String line=b.readLine();

First, you will want to make sure that any file reading objects are always properly cleaned up.首先,您需要确保任何文件读取对象始终被正确清理。 A try-with-resources block is your best bet, or otherwise a try finally block. try-with-resources块是您最好的选择,否则尝试 finally 块。

try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
        new FileInputStream(file))) {
    //code using bufferedReader goes here.
}

You should not need to use the Pattern class here.您不需要在此处使用Pattern类。 It's a simple case of reading a line and using the String.split method.这是读取一行并使用String.split方法的简单案例。 eg例如

String line = bufferedReader.readLine();
//if (line == null) throw an exception
String[] splitLine = line.split("\\s+");

Now the splitLine variable will contain an array of Strings, which is each of the elements from the original line, as separated by spaces.现在splitLine变量将包含一个字符串数组,它是原始行中的每个元素,由空格分隔。 The split method takes a String which is the regular expression representing the 'delimiter' of your values. split方法采用一个String ,它是表示值的“分隔符”的正则表达式。 For more information on regular expressions in Java, try this .有关 Java 中正则表达式的更多信息,请尝试 The "\\\\s+" represents any whitespace character or characters These can be 'parsed' to int values using the Integer.parseInt method, like this: "\\\\s+"表示任何空白字符或字符这些可以使用Integer.parseInt方法“解析”为int值,如下所示:

int[] a = new int[splitLine.length];
for(int i = 1; i <= splitLine.length; i++) {
    int parsed = Integer.parseInt(splitLine[i]);
    a[splitLine.length - i] = parsed;
}

The parseInt method may throw a NumberFormatException , for example if you give it the String "Hello world" . parseInt方法可能会抛出NumberFormatException ,例如,如果你给它字符串"Hello world" You can either catch that or let it be thrown.你可以抓住它或者让它被扔掉。

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

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