Java 缓冲读取器/文件读取器.readLine()到.split()读取,但不显示到控制台
我已经把它精简到最低限度,似乎无法解决这个问题。我做了很多查询,尝试了无数次迭代。因此,任何建议都将不胜感激。我使用for循环查看我希望从输入文件获得的数组的输出(只是一个数字列表;行的范围从1位到6位)。理想情况下,这些行需要读取,输出到一个数组中,逐整数。非常感谢Java 缓冲读取器/文件读取器.readLine()到.split()读取,但不显示到控制台,java,filereader,Java,Filereader,我已经把它精简到最低限度,似乎无法解决这个问题。我做了很多查询,尝试了无数次迭代。因此,任何建议都将不胜感激。我使用for循环查看我希望从输入文件获得的数组的输出(只是一个数字列表;行的范围从1位到6位)。理想情况下,这些行需要读取,输出到一个数组中,逐整数。非常感谢 public static void main(String[] args) throws IOException { String line = ""; int matrix[][] = new int[0][
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();
}
}
}
publicstaticvoidmain(字符串[]args)引发IOException{
字符串行=”;
整数矩阵[][]=新整数[0][];
String text=“line1\n\n\nline4”;
int lineNumber=0;
试一试{
FileReader FileReader=newFileReader(“input.txt”);
BufferedReader BufferedReader=新的BufferedReader(文件阅读器);
while((bufferedReader.readLine()!=null)){
字符串stringArray[]=line.split(“”);
对于(int x=0;x如果您打算将文件作为矩阵读取(每行是一个单独的整数数组),此方法可能会有帮助:
/**
* 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();
}
}
您没有读取该行,请尝试将while((bufferedReader.readLine()!=null))替换为while((line=bufferedReader.readLine())!=null)
谢谢!我在第一百万次迭代中错过了一件愚蠢的事情。我确实尝试了readMatrix方法。但是当我在main中设置path来调用该方法时,我遇到了一个数字异常错误。我已经有一段时间没有使用path了,所以我不确定出了什么问题。path path1=Paths.get(“\\Lab2”,“\\input.txt”);readMatrix(path1);@SadieRose我想这与输入文件中的空行有关。当检测到空行时,您想做什么?忽略它或为此行返回一个空数组?@SadieRose更新了原始答案,空行现在被忽略。
Files.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.map(line -> line.split("\\s+"))
.flatMapToInt(tokens -> Arrays.stream(tokens)
.mapToInt(Integer::parseInt))
.toArray();