Java 从文件读取输入
如何从文件中读入输入并将其保存到数组中? 例如,该文件包含: 二, 1 12 3 2 4 5 其中,第一个数字(2)表示所需的阵列数。 第二行中的第一个数字是数组ID,后跟数组中应包含的内容(1 2 3)。第三行也是如此,所以数组2应该包含4和5 因此,这两个阵列应该是: 阵列1:[1][2][3] 阵列2:[4][5]Java 从文件读取输入,java,arrays,input,Java,Arrays,Input,如何从文件中读入输入并将其保存到数组中? 例如,该文件包含: 二, 1 12 3 2 4 5 其中,第一个数字(2)表示所需的阵列数。 第二行中的第一个数字是数组ID,后跟数组中应包含的内容(1 2 3)。第三行也是如此,所以数组2应该包含4和5 因此,这两个阵列应该是: 阵列1:[1][2][3] 阵列2:[4][5] 请用爪哇!谢谢 您可以将所有数字存储在整数数组中: public static void main(String[] args) { try (BufferedRea
请用爪哇!谢谢 您可以将所有数字存储在整数数组中:
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("c:\\temp\\text.txt"))) {
int numberOfArrays = Integer.parseInt(reader.readLine());
int[][] arrays = new int[numberOfArrays][];
int i = 0;
while (i < numberOfArrays) {
String line = reader.readLine();
if (line.isEmpty()) {
continue;
}
String[] parts = line.split(" ");
int[] lineNumbers = new int[parts.length - 1];
// is "array id" really necessary? i am just ignoring it.
for (int j = 0; j < lineNumbers.length; j++) {
lineNumbers[j] = Integer.parseInt(parts[j + 1]);
}
arrays[i++] = lineNumbers;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
publicstaticvoidmain(字符串[]args){
try(BufferedReader=new BufferedReader(new FileReader(“c:\\temp\\text.txt”)){
int numberOfArrays=Integer.parseInt(reader.readLine());
int[][]数组=新的int[numberOfArrays][];
int i=0;
while(i
我建议使用java8。读取文件的所有行变得很容易。并且转换等可以很容易地用流来解决
未经测试的示例代码:
private static int[][] read() {
Path path = Paths.get("c:/temp", "data.txt");
try (Stream<String> lines = Files.lines(path)) {
return lines
// remove first line
.skip(1)
// convert line to array
.map(l -> l.split(" "))
// remove first colum
.map(a - > Arrays.copyOfRange(a, 1, a.length))
// convert to array
. collect(Collectors.toArray());
}
}
private static int[]read(){
Path Path=Path.get(“c:/temp”、“data.txt”);
try(流行=文件。行(路径)){
回程线
//删除第一行
.skip(1)
//将行转换为数组
.map(左->左拆分(“”)
//拆下第一根立柱
.map(a->Arrays.copyOfRange(a,1,a.length))
//转换为数组
.collect(collector.toArray());
}
}
我们在这里做家庭作业吗?不,只是玩得开心,@SleimanJneidi