2016-06-14 88 views
-4

我最近偶然發現了這個問題。我想在一個文件中存儲一個2維的int數組以便稍後讀取。除了簡單的txt.file之外,還有其他方法嗎?這是我的第一篇文章,請原諒我的英文。 (Java作爲編程語言)2維陣列存儲

+3

所有數組都是可序列化的(只要它們的元素是'int'就是這種情況)。只需用'ObjectOutputStream'編寫它;用ObjectInputStream讀回它。 –

回答

0

正如@Andy表明您可以使用ObjectOutputStream序列化數組到一個文件

int[][] intArray = new int[5][5]; 
//Code to populate array 

// serialize array 
FileOutputStream fos = new FileOutputStream("array.dat"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(intArray); 

然後它可以使用回讀從文件的數組ObjectInputStream

FileInputStream fis = new FileInputStream("array.dat"); 
ObjectInputStream iis = new ObjectInputStream(fis); 
intArray = (int[][]) iis.readObject(); 

希望這會有所幫助。