2015-02-10 47 views
1

所以,基本上,我將有一個名爲 「data.txt中」讀取.TXT信息,並將其加載到一個數組

此文件將包含

Name;Age;State 

Anne;19;S (Single/Married/etc) 
Gustav;18;S 
Dinisio;19;C 

基本上,我想讀取文件,將信息放入數組,並顯示/列出它,例如:

Name: Anne 
Age: 19 
State: S 

Name: Gustav 
Age: 18 
State: S 

Name: Dinisio 
Age: 19 
State: C 

對於我做了一個類的結構如下:

class Person { 
    String name; 
    int age; 
    char state; 
    } 

變量:

int i, option; 
    String s; 
    File f = new File("C:\\Users\\Gustavo\\Desktop\\data.txt"); 

    Person arrayPerson[] = new Person[4]; // It has 4 persons only 

我有以下菜單:

System.out.print("Choose an option: "); 
    System.out.println("\n1- Load"); 
    System.out.println("2- List"); 
    System.out.print("Option: "); 
    option= ler.nextInt(); 
    System.out.println(""); 

    switch(option) 
    { 
     case 1: 
     { 
      Exercicio07Java.openRead(f); 
      while((s = Exercicio07Java.readLine()) != null) 
      { 
       String[] str = s.split(";"); 
       arrayPerson[i] = new Person(); 
       arrayPerson[i].name = str[0]; 
       arrayPerson[i].age = Integer.valueOf(str[1]); 
       arrayPerson[i].state = str[2].charAt(0); 
       i++; 
      } 
      Exercicio07Java.closeRead(); 
      break; 
     } 

     case 2: 
     { 
      for(i = 0; i < 4; i++) 
      { 
       System.out.println(arrayPerson[i].nome); 
       System.out.println(arrayPerson[i].idade); 
       System.out.println(arrayPerson[i].estado); 
      } 
      break; 
     } 
    } 

我知道更多或更少如何閱讀信息但我不知道如何將它傳遞給一個數組,而它被分開;

任何想法?

+3

開始生成具有仰視String.split(字符串數組「;」 ); – DHerls 2015-02-10 17:09:41

+3

只是谷歌「讀取逗號分隔文件Java」,你會得到數百教程 – Setu 2015-02-10 17:09:44

+1

可能的重複[如何從文本文件中讀取逗號分隔值在JAVA?](http://stackoverflow.com/questions/10960213/how-逗號分隔值 - 從文本文件在Java) – Setu 2015-02-10 17:12:39

回答

1

使用String.Split(字符串分隔符),它返回一個字符串[]。如果你將整行讀成一個字符串並創建一個新人。見下文。這可能是一個尋找你的好地方。

for(int i = 0; i < persons.size(); i++) { 
    String [] info = /**Line From File Here As A String*/.split(";"); 
    persons[i].name = info[0]; 
    persons[i].age = info[1]; 
    persons[i].state = info[2]; 
} 
+1

您必須將信息[1]和信息[2]轉換爲正確的數據類型。 – IByrd 2015-02-10 17:20:25

+0

我已將我的帖子編輯到我的實際代碼中,是否因爲它有一段時間不工作?或者是別的什麼? – Ran 2015-02-10 17:38:59

+0

我不確定究竟在問什麼。但是,我認爲你有什麼應該游泳。 – IByrd 2015-02-10 17:48:41

1

所以說,如果你有四行例如,你可以這樣做:

int index = 0; 
while//read line in a file { 
    String[] str = lineFromFile.split(";");//will split line on semicolon and you have name in index 0 of array, age in index 1 of str array and so on 
    //validate you have all three parameters that you need to create person object. 
    Person person = new Person(str[0], convertToInt(str[1]), str[2].charAt(0));//assuming you have constructor that accepts name, converted method to convert age to integer, state 
    arrayPerson[index++]=person; 
} 
0

您可以使用bufferedreader進行讀取行和split;標記 並在此之後 設置arrayproperty等 arrayPerso [I]。名稱=溫度[0] //這裏溫度是被用於拆分值存儲

相關問題