2016-04-15 72 views
-4

我有一個看起來像43 78 63 73 99 ....的.txt文件,即 所有的值都由空格分隔。 我想把它們中的每一個都加入到一個數組中,這樣 a[0]=43 a[1]='78 a[2]=63等等。 我該如何在Java中執行此操作..請解釋將txt文件的內容存儲在數組中

+0

純粹的代碼寫入請求在堆棧溢出上偏離主題 - 我們期望 這裏的問題與*特定的*編程問題有關 - 但我們 會很高興地幫助您自己編寫它!告訴我們 [你試過的東西](http://stackoverflow.com/help/how-to-ask),以及你卡在哪裏。 這也將幫助我們更好地回答你的問題。 –

回答

0

將文件讀入字符串。然後將空間中的字符串溢出到字符串數組中。

0

嗯,我會用文本文件存儲到一個字符串做到這一點。 (只要它不太大)然後我會使用.split(「」)將它存儲到一個數組中。

像這樣:

String contents = "12 32 53 23 36 43"; 
//pretend this reads from file 

String[] a = contents.split(" "); 

現在陣 'A' 應該存儲在其中的所有值。如果你想讓數組成爲一個int,你可以使用一個int數組,並使用Integer.toString()來轉換數據類型。

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

public class readTextToIntArray { 
public static void main(String... args) throws IOException { 
    BufferedReader reader=new BufferedReader(new FileReader("/Users/GoForce5500/Documents/num.txt")); 
    String content; 
    List<String> contentList=new ArrayList<String>(); 
    while((content=reader.readLine())!=null){ 
     for(String column:content.split(" ")) { 
      contentList.add(column); 
     } 
    } 
    int[] result=new int[contentList.size()]; 
    for(int x=0;x<contentList.size();x++){ 
     result[x]=Integer.parseInt(contentList.get(x)); 
    } 
} 
} 

您可以使用它。

+0

幫助初學者時,通常最好提供解釋,而不是隻發佈編譯的代碼。 – Signal

相關問題