[英]How to read certain parts of a file and store it into an array in java
所以我目前有一个名为Hotel的String数组。 在此数组中,元素包含入住酒店的人的姓名。 (我编写了一个while循环,用户只需输入房间号和名称。房间号对应于数组索引,并且名称包含该特定索引的元素。例如3 Jim,在数组中,第四个索引为我不能使用arraylist,而只能使用array ..我已经提交了部分规格)。
这是整个程序的一部分。 这是我编写的将数组数据保存到文件中的方法:
private static void savingToFile(String[] hotelRef) {
System.out.println("Creating a text file called Hotel Data");
File fileObject = new File("C://Hotel_Data.txt");
if (!fileObject.exists()) {
try {
fileObject.createNewFile();
System.out.println("File has been created in the C directory");
} catch (IOException e) {
System.out.println("Something went wrong in the process " + e);
}
}
try {
FileWriter fs = new FileWriter(fileObject);
BufferedWriter writer = new BufferedWriter(fs);
for (int i = 0; i < hotelRef.length; i++) {
String hoteldata = i + " " + hotelRef[i];
writer.write(hoteldata);
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("Something went wrong " + e);
}
}
我已经运行了程序,它运行正常。 输出一个文件,其中包含房间号和该房间中当前居住的人的名字。 现在,我需要制作另一种方法,可以将文件中的数据加载到数组中,但是我不知道如何获取文件中的各个部分。 例如,我不知道如何仅从数据中获取名称而不获取房间号。
只需读取文件并使用String.split方法即可获取房间号和名称。 像这样:
String[] hotelRef = new String[MAX_NO_OF_ROOMS];
FileInputStream in = new FileInputStream("Hotel_Data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String hotelLine;
while((hotelLine = br.readLine())!= null)
{
//split the line contents
String hotelLineItems[] = hotelLine.split("\\s");
Integer roomNo = Integer.valueOf(hotelLineItems[0]);
String name = hotelLineItems[1];
hotelRef[roomNo] = name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.