2015-04-05 84 views
0

如何將文件讀入String []數組然後將其轉換爲ArrayList?將文本文件讀入String數組,然後轉換爲ArrayList

我無法馬上使用ArrayList,因爲我的列表類型不適用於參數(字符串)。

所以我的教授告訴我把它放入一個String數組中,然後將其轉換。

我很難過,因爲我對Java仍然很陌生,所以無法理解我的生活。

+0

好像http://stackoverflow.com/questions/19844649/java-read-file-and-store-text-in-an-array的副本。一般來說,對於一個數組轉換成一個列表,你可以使用'Arrays.asList(myarray的);' – 2015-04-05 23:53:09

+0

我不斷收到錯誤「無法轉換列表列出 ...... ArrayList中持有Person對象FYI – 2015-04-06 00:12:23

+0

它如果你分享了相關的代碼,將會有所幫助,但總之,如果不明確地填充每個'Person',你就不能從文件中讀入'Person'列表,最簡單的方法是先讀取「raw」字符串行,之後再進行line - >'Person'的轉換。 – 2015-04-06 00:15:44

回答

0
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by tsenyurt on 06/04/15. 
*/ 
public class ReadFile 
{ 
    public static void main(String[] args) { 

     List<String> strings = new ArrayList<>(); 
     BufferedReader br = null; 

     try { 

      String sCurrentLine; 

      br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml")); 

      while ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(sCurrentLine); 
       strings.add(sCurrentLine); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 
} 

有讀取一個文件並創建一個ArrayList的一個代碼,它

http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

0

那麼有很多方法可以做到這一點, 如果你想有一個你可以使用此代碼每個單詞的列表中文件存在

public static void main(String[] args) { 
    BufferedReader br = null; 
    StringBuffer sb = new StringBuffer(); 
    List<String> list = new ArrayList<>(); 
    try { 

     String sCurrentLine; 

     br = new BufferedReader(new FileReader(
       "Your file path")); 

     while ((sCurrentLine = br.readLine()) != null) { 
      sb.append(sCurrentLine); 
     } 
     String[] words = sb.toString().split("\\s"); 
     list = Arrays.asList(words); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null) 
       br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    for (String string : list) { 
     System.out.println(string); 

    } 
} 
相關問題