Java: 如何从输入文件中读取和存储数据?
Java: How do I read and store data from input file?
我需要存储来自具有以下形式的输入文件的数据:
k=5
1: 62 35
2: 10 49
1 Banana
2 Apple
我需要将 k 的值存储为一个 int,然后我需要将接下来两行的 int 值存储为一个 [2][2] 数组,最后我需要字符串 "Banana" 和 "Apple" 存储在列表中。我尝试使用 useDelimiter 但它忽略了我的定界符并将整行作为一行实例读取。
public static void main(String[] args) {
File file = new File("input.text");
try {
Scanner scanner = new Scanner(file);
scanner.useDelimiter("n=");
scanner.useDelimiter(".:");
int k = scanner.nextLine();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
array[i][j] = scanner.nextInt();
}
} scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
如果文本始终具有相同的结构,那么您可以这样做
int k = Integer.parseInt(scanner.nextLine().substring("=")[1]);
String currentLine;
for (int i = 0; i < 2; i++)
currentLine = scanner.nextLine().substring(currentLine.indexOf(" ") + 1)
for (int j = 0; j < 2; j++)
array[i][j] = currentLine.split(" ")[j];
}
}
然后对于香蕉和苹果的解析,应用相同的逻辑。子字符串直到从第一个 space + 1 个字符的索引开始,因为我们不想保留它。然后将该字符串添加到您的列表中。
我需要存储来自具有以下形式的输入文件的数据:
k=5
1: 62 35
2: 10 49
1 Banana
2 Apple
我需要将 k 的值存储为一个 int,然后我需要将接下来两行的 int 值存储为一个 [2][2] 数组,最后我需要字符串 "Banana" 和 "Apple" 存储在列表中。我尝试使用 useDelimiter 但它忽略了我的定界符并将整行作为一行实例读取。
public static void main(String[] args) {
File file = new File("input.text");
try {
Scanner scanner = new Scanner(file);
scanner.useDelimiter("n=");
scanner.useDelimiter(".:");
int k = scanner.nextLine();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
array[i][j] = scanner.nextInt();
}
} scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
如果文本始终具有相同的结构,那么您可以这样做
int k = Integer.parseInt(scanner.nextLine().substring("=")[1]);
String currentLine;
for (int i = 0; i < 2; i++)
currentLine = scanner.nextLine().substring(currentLine.indexOf(" ") + 1)
for (int j = 0; j < 2; j++)
array[i][j] = currentLine.split(" ")[j];
}
}
然后对于香蕉和苹果的解析,应用相同的逻辑。子字符串直到从第一个 space + 1 个字符的索引开始,因为我们不想保留它。然后将该字符串添加到您的列表中。