2013-04-16 59 views
0

我正在使用DataStream封裝FileStream在兩個不同的應用程序之間發送大位圖(Intents有1mb的限制,我不想將文件保存到文件系統),使用FileInputStream和File對象代替命名管道的問題

我的問題是DataInputStream拋出一個EOFException當流仍然打開,但沒有數據。我期望這會簡單地阻止(雖然文檔在這個問題上非常含糊)。

DataOutputStream類:

public void onEvent() { 
    fos.writeInt(width); 
    fos.writeInt(height); 
    fos.writeInt(newBuffer.length); 
    fos.write(newBuffer); 
} 

DataInputStream類:

while(true) { 
    int width = fis.readInt(); 
    int height = fis.readInt(); 
    int length = fis.readInt(); 
    byte[] bytes = new byte[length]; 
    fis.read(bytes); 
} 

任何人都可以提出一個更好的組類,從一個線程流數據到另一個(其中,閱讀()/的readInt()成功塊)。

編輯

我試着從方程式去除DataInputStreamDataOutputStream通過簡單地使用FileInputStreamFileOutputStream熨平了這一點:

fos.write(intToByteArray(width)); 
    fos.write(intToByteArray(height)); 
    fos.write(intToByteArray(newBuffer.length)); 
    Log.e(this.class.getName(), "Writing width: " + Arrays.toString(intToByteArray(width)) + 
                 ", height: " + Arrays.toString(intToByteArray(height)) + 
                 ", length: " + Arrays.toString(intToByteArray(newBuffer.length))); 
    fos.write(newBuffer); 
    if(repeat == -1) { 
     Log.e(this.class.getName(), "Closing ramFile"); 
     fos.flush(); 
     fos.close(); 
    } 

這給:

Writing width: [0, 0, 2, -48], height: [0, 0, 5, 0], length: [0, 56, 64, 0]

並在另一邊,我用這個:

while(true) { 
    byte[] intByteArray = new byte[] { -1,-1,-1,-1 }; 
    fis.read(intByteArray); 
    Log.e(this.class.getName(), Arrays.toString(intByteArray)); 
    int width = toInt(intByteArray, 0); 
    fis.read(intByteArray); 
    int height = toInt(intByteArray, 0); 
    fis.read(intByteArray); 
    int length = toInt(intByteArray, 0); 
    Log.e(this.class.getName(), "Reading width: " + width + ", height: " + height + ", length: " + length); 
} 

其中給出:

[0, 0, 2, -48] 
Reading width: 720, height: 1280, length: 3686400 

,然後奇怪的是,read()不阻止,它只是進行歡快,不堵但不填充任何值在數組中(初始化數組{9,9,9,9}在讀取後仍然是9,9,9,9)。

[-1, -1, -1, -1] 
Reading width: -1, height: -1, length: -1 
java.lang.NegativeArraySizeException: -1 

這是什麼瘋狂的感覺?

回答

0

這裏相當簡單的答案(這是沒有很好的記錄)。

FileInputStream沒有超時,因爲它的read請求 - 意思是說,如果你從一個空的但未關閉的流中讀取它,它將返回而不填寫字節(留下字符「按原樣」)。

您可以使用LocalSocketLocalServerSocket將數據流通過相同的機制,並使用

LocalServerSocket server = new LocalServerSocket(SOCKET_NAME); 
LocalSocket socket = server.accept(); 
socket.setSoTimeout(60); 

這將迫使60秒超時您所讀操作(阻塞,直到數據可用)。