簡體   English   中英

如何讀取文件的某些部分並將其存儲到Java中的數組中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM