2013-10-23 28 views
0

我正在使用此代碼寫入文件,並且它會拋出IndexOutOfBoundException寫入文件時發生IndexOutOfBoundException

InputStream is = res.openStream(); 
FileOutputStream fos = new FileOutputStream(file); 
byte[] array = new byte[1024]; 
for(int i = is.read(array); i != 1; i=is.read(array)) { 
     fos.write(array, 0, i); 
} 

我該如何檢查留下了多少字節?

+0

只有當我與'1'不同時,您的for循環纔會中斷。當沒有東西可讀時,'is.read'方法返回-1。 – Matthias

+0

哇我錯過了某種方式 –

+0

它通常是容易錯過的小東西:)一直髮生在大家身上。 – Matthias

回答

3

當沒有東西可讀時,read方法返回-1而不是1。 因此,您的循環中的檢查必須是:

for(int i = is.read(array); i != -1; i=is.read(array)) 
相關問題