2013-03-20 113 views
0

我想將文本文件列表讀取到二維數組中。該代碼在讀入數組時會拋出運行時錯誤。我怎樣才能解決這個問題?將文本文件讀入二維數組?

public static void main(String[] args) throws IOException 
    {  
    byte[][] str = null; 
    File file=new File("test1.txt"); 
    str[0]= readFile1(file); 

    File file2=new File("test2.txt"); 
    str[1]= readFile1(file2); 
    } 

public static byte[] readFile1 (File file) throws IOException { 

    RandomAccessFile f = new RandomAccessFile(file, "r"); 

    try {  
     long longlength = f.length(); 
     int length = (int) longlength; 
     if (length != longlength) throw new IOException("File size >= 2 GB"); 

     byte[] data = new byte[length]; 
     f.readFully(data); 
     return data; 
    } 
    finally { 
     f.close(); 
     } 
    } 
+1

**錯誤說**是什麼? – SLaks 2013-03-20 03:21:20

+0

1)*「拋出運行時錯誤」*通過複製/粘貼堆棧跟蹤作爲[編輯問題](http://stackoverflow.com/posts/15514690/edit)將其縮小。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-03-20 03:21:28

回答

2

要與

byte[][] str = null; 
File file=new File("test1.txt"); 
str[0]= readFile1(file); 

開始的最後一條語句將拋出NullPointerException因爲str在這一點空。您需要分配陣列:

byte[][] str = new byte[2][];