我一直在用这个;一种单行:
public static String[] ReadFileToStringArray(String ReadThisFile) throws FileNotFoundException{
return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").next()).split("[\\r\\n]+");
}
要读取具有此类内容的文件(即具有字符串标记):
abcd
abbd
dbcd
但是,现在我的文件内容是这样的:
1 2 3 4
1 2 2 4
1 5 3 7
1 7 3 8
我希望这些值被读取为整数。
我尝试了以下方法但失败了:
public static int[][] ReadFileToMatrix(String ReadThisFile) throws FileNotFoundException{
return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+");
}
错误消息: 无法在基本类型 int
上调用 split(String)
。 我理解该消息并且知道这是非常错误的:)
任何人都可以提出实现这一目标的正确方法吗?
附注恕我直言,对带有循环的解决方案说“不”。
最佳答案
当基本 BufferedReader
时使用类似乎过于复杂与 Integer.parseInt(line.split(" ")[n]);
会做。
关于java - 用于从文件中读取矩阵的单行 Java 扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28985526/