2016-02-05 71 views
0

我有一個文件,可以讀取它的內容。現在我想將每個單獨的行分割成一個arrayList,並且不能成功。將文件內容分割成ArrayList

這是我迄今爲止

try { 
     input = new FileInputStream(test); 


     byte testContent[] = new byte[(int) test.length()]; 
     input.read(testContent); 


     String testFile = new String(testContent); 
     System.out.println(testFile); 

    } 

的文件內容的例子如下,

0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0 0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1 0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1 0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1 0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1

我想上面的是在陣列像

[0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0] [0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1] [0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1] [0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1] [0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1]

預先感謝任何幫助

+2

使用'BufferedReader'逐行閱讀;使用'String.split'分割各條線。 –

+2

你也可以使用'split()' – user3282276

+0

你可以說可以使用Scanner,但我認爲這裏最有效的東西是讀取整行,然後拆分爲@AndyTurner建議。 – Neil

回答

0
String [] lines = testFile.split("\\r?\\n"); 
1

如何Files.readAllLines()

List<String> lines = Files.readAllLines(new File(test).toPath()); 

如果您使用的是Java 7,你需要這個版本:

List<String> lines = Files.readAllLines(new File(test).toPath(), StandardCharsets.UTF_8); 
+0

add也自1.8 – awsome

+1

@awsome編輯。 – shmosel

0

你可以嘗試這樣的事情:

BufferedReader br = new BufferedReader(new FileReader(yourFile)); 
List<String[]> listOfArrays = new ArrayList<String[]>(); 

String nextLine; 
while((nextLine = br.readLine()) != null){ 

    String[] lineArray = nextLine.split(","); 
    listOfArrays.add(lineArray); 

} 
0
I wrote the following code which will meet your requirement. You just need to replace the file whith your file 

public static void main(String[] args) throws FileNotFoundException, 
      IOException { 
     BufferedReader br = new BufferedReader(
       new FileReader(
         "C:\\Users\\yati_Sawhney\\workspace\\practice\\src\\practice\\yates.txt")); 
     String curLine = null; 
     ArrayList<String> al = new ArrayList<String>(); 
     while ((curLine = br.readLine()) != null) { 
      al.add(curLine); 
     } 

     for (Iterator iterator = al.iterator(); iterator.hasNext();) { 
      String string = (String) iterator.next(); 
      System.out.println(string); 

     } 
     br.close(); 

    }