缓冲的读取器/文件读取器.readLine()到.split()的读取,但没有控制台显示

时间:2018-07-20 02:37:45

标签: java filereader

我已将其减少到最低限度,似乎无法解决问题。我已经做了很多询问,并尝试了无数次迭代。因此,任何建议将不胜感激。我使用了for循环来查看希望从输入文件中获取的数组输出(只是数字列表;行的范围是1位数到6位数)。理想情况下,需要将行以int的方式读入数组。非常感谢!

public static void main(String[] args) throws IOException {

    String line = "";
    int matrix[][] = new int[0][];
    String text = "line1\n\n\nline4";
    int lineNumber = 0;

    try {
        FileReader fileReader = new FileReader("input.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while ((bufferedReader.readLine() != null)) {

            String stringArray[] = line.split(" ");
            for(int x = 0; x <= stringArray.length-1; x++) {
                System.out.println(stringArray[x]);
                System.out.printf("%04d: %s%n", ++lineNumber, line);
                System.out.println("here");
            }
        }

        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

输入的代码段:   enter image description here

输出片段:

0001: 这里

0002: 这里

0003: 这里

1 个答案:

答案 0 :(得分:0)

如果您打算以矩阵形式读取文件(每行一个单独的整数数组),则此方法可能会有所帮助:

/**
 * Read a matrix from the specified path, each line corresponds to a 
 * separate array of integers.
 * 
 * @param path the path to the file, not null
 * @return a matrix, not null
 * @throws IOException           if an I/O error occurs opening the file
 * @throws NumberFormatException if the file contains non-parsable integers
 */
public static int[][] readMatrix(Path path) throws IOException
{
    Objects.requireNonNull(path);

    try (Stream<String> lines = Files.lines(path))
    {
        return lines
                .map(String::trim) // Remove leading and trailing whitespaces.
                .filter(line -> !line.isEmpty()) // Ignore empty lines.
                .map(line -> line.split("\\s+")) // Split line by whitespaces.

                // Map tokens of type String[] to int[]
                .map(tokens -> Arrays.stream(tokens)
                        .mapToInt(Integer::parseInt) // Throws NumberFormatException if not parsable
                        .toArray())
                .toArray(int[][]::new);
    } catch (UncheckedIOException e)
    {
        throw e.getCause();
    }
}

如果您只对整数数组感兴趣,并且不关心按行分割它们:

Files.lines()
    .map(String::trim)
    .filter(line -> !line.isEmpty())
    .map(line -> line.split("\\s+"))
    .flatMapToInt(tokens -> Arrays.stream(tokens)
            .mapToInt(Integer::parseInt))
    .toArray();