2016-02-15 146 views
3

我需要從txt文件中讀取有關汽車的信息,然後將其保存到ArrayList。文件中的第一行告訴你文件中有多少輛汽車。從多個對象的文本文件創建對象

txt文件看起來是這樣的:

3 
2011 
Toyota 
Corolla 
2009 
Honda 
Civic 
2012 
Honda 
Accord 

等..

我知道如何創建一個從用戶輸入的對象,但我想編輯它因此從讀它一份文件。

+1

請包括您現在的代碼以及確切的問題。 –

回答

3

通常我會建議使用FileReader,但你說你重構了從用戶那裏讀取這些信息的代碼。我想,你是一個Scanner讀取輸入,所以要改變這種最簡單的方法就是用這種替代

Scanner sc = new Scanner(System.in); 

Scanner sc = new Scanner(new File("someFile.txt")); 

然後,您可以使用Scanner這樣的:

String fileName = "cars.txt"; 
List<Car> cars = new ArrayList<>(); 
try (Scanner sc = new Scanner(new File("someFile.txt"))){ 
    int count = sc.nextInt(); 
    for (int i = 0; i < count; i++) { 
     int year = sc.nextInt(); 
     String brand = sc.next(); 
     String type = sc.next(); 
     cars.add(new Car(year, brand, type)); 
    } 
} catch (IOException e) { 
    System.err.println("error reading cars from file "+fileName); 
    e.printStackTrace(); 
} 

在您從Scanner讀取之前,還需要使用sc.hasNext()sc.hasNextInt(),因爲您的代碼否則可能會拋出異常,如果該文件沒有有效的內容..

你可以看到在另一個(不同的)答案我張貼

+0

我已經做了那部分,我知道如何閱讀文本文件。我遇到的問題是我想保存汽車的每一部分;年份,名稱,型號。然後我需要使用這些保存的變量並與它們建立對象。 – BMW

+0

我添加了使用'Scanner'來讀取值 –

+0

的部分,並請考慮對任何有幫助的答案進行upvoting。如果有人發佈了,也不要忘記接受正確的答案! –

2

如果你不只是要重構它使用的代碼的Car類一個Scanner,你可以用一個FileReader做到這一點:

String fileName = "cars.txt"; 
List<Car> cars = new ArrayList<>(); 
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))){ 
    int count = Integer.parseInt(reader.readLine()); 
    for (int i = 0; i < count; i++) { 
     int year = Integer.parseInt(reader.readLine()); 
     String brand = reader.readLine(); 
     String type = reader.readLine(); 
     cars.add(new Car(year, brand, type)); 
    } 
} catch (IOException | NumberFormatException e) { 
    System.err.println("error reading cars from file "+fileName); 
    e.printStackTrace(); 
} 

請注意,你可能需要做適當的錯誤處理的catch塊。此外,他到達文件的結尾,讀者可能會返回null,以防萬一你想驗證輸入從文件來(你應該這樣做)..

,這是你Car類:

public class Car { 
    private final int year; 
    private final String brand; 
    private final String type; 

    public Car(int year, String brand, String type) { 
     this.year = year; 
     this.brand = brand; 
     this.type = type; 
    } 

    public int getYear() { 
     return year; 
    } 

    public String getBrand() { 
     return brand; 
    } 

    public String getType() { 
     return type; 
    } 
} 
+0

因爲我過去的經歷不好:請注意,如果您有兩個截然不同的答案,它不僅被接受,[但期望](http://meta.stackexchange.com/a/25210/316262)可以回答兩次 –