我一直在使用这个;一种单行:
public static String[] ReadFileToStringArray(String ReadThisFile) throws FileNotFoundException{
return (new Scanner( new File(ReadThisFile) ).useDelimiter("\A").next()).split("[\r\n]+");
}
要读取具有此类内容(即使用字符串标记)的文件:
美国广播公司
阿布德
DBCD
但是,现在我的文件内容是这样的:
1 2 3 4
1 2 2 4
1 5 3 7
1 7 3 8
我希望这些值被读取为整数。
我已经看到了这 1、2 和 3 个问题,但它们没有回答我的问题。
我尝试了以下方法,但失败了:
public static int[][] ReadFileToMatrix(String ReadThisFile) throws FileNotFoundException{
return (new Scanner( new File(ReadThisFile) ).useDelimiter("\A").nextInt()).split("[\r\n]+");
}
错误消息:无法在基元类型 int
上调用split(String)
。我理解这个信息,并且知道这是非常错误的:)
任何人都可以提出实现这一目标的正确方法。
附言恕我直言,对带有循环的解决方案说"不"。
当具有Integer.parseInt(line.split(" ")[n]);
的基本BufferedReader
时,使用类似乎过于复杂。
如果你使用Java 7或更高版本,你可以使用这样的东西。我想不出一种在没有循环的情况下在一行中做到这一点的方法。只需将其放入方法中并调用它即可。
//Read full file content in lines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int NR_OF_COLUMNS = 4;
int NR_OF_ROWS = lines.size();
int[][] result = new int[NR_OF_ROWS][NR_OF_COLUMNS];
for(int rowIndex = 0; rowIndex < NR_OF_ROWS; rowIndex++)
{
String[] tokens = lines.get(rowIndex).split("\s+"); //split every line
for(int columnIndex = 0; columnIndex < NR_OF_COLUMNS; columnIndex++)
result[rowIndex][columnIndex] = Integer.parseInt(tokens[columnIndex]); //convert every token to an integer
}
return result;
在 Java 8 中,您可以使用 Lambdas:
public static int[][] readFileToMatrix(String readThisFile) throws FileNotFoundException{
return Arrays.stream((new Scanner( new File(readThisFile) ).useDelimiter("\A").nextInt()).split("[\r\n]+")).mapToInt(Integer::parseInt).toArray();
}
否则,如果没有循环,您将无法做到这一点。您有一个 String[]
数组,并且您希望为每个元素逐个调用Integer.parseInt()
。