[英]sending image from java server to android app
我想使用以下代碼將圖像文件從 java 服務器發送到 android 應用程序:
服務器(Java):
File file = new File("./clique.jpg");
FileInputStream stream = new FileInputStream(file);
DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
byte[] contextB = new byte[4096];
int n;
int i = 0;
while ( (n=stream.read(contextB))!=-1 ){
writer.write(contextB, 0, n);
writer.flush();
System.out.println(n);
i+=n;
}
writer.flush();
stream.close();
android 應用程序:
DataInputStream reader = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[4096];
ByteArrayOutputStream content = new ByteArrayOutputStream();
int n;
int i = 0;
reader = new DataInputStream(socket.getInputStream());
while ( (n=reader.read(buffer)) != null){
content.write(buffer, 0, n);
content.flush();
}
Utility.CreateImageFile(content.toByteArray());
我注意到的是,在 android 應用程序 n 中,當我從 4096 大小的服務器字節塊發送時,讀取字節數不是 4096,我也無法得到 n=-1,這是 stream 的結尾,它阻塞直到我關閉應用程序然后我得到 n = -1。
關於您一次讀取的字節數與您寫入的字節數無關 - 它在很大程度上取決於網絡條件,並且會隨着每個塊而變化(基本上與在短時間內設法傳輸的字節數一樣多)讀取之間的時間與您將在讀取塊中獲得的時間一樣多。
Regarding the end of stream - in your server code you have forgotten to close the output stream (you only close the stream which is input stream - you should also close the writer which in turn will close the underlying output stream.
兩條評論:
1)我真的建議使用緩沖的讀取器/寫入器來包裝寫入/讀取器 - 您將獲得的代碼會更好,您不必自己創建/管理緩沖區。
2) 使用 try {} finally 並在 finally 子句中關閉您的流 - 這是確保您將關閉流並釋放資源的最佳實踐,即使在讀/寫時出現問題也是如此。
您的 android 代碼有問題:
while ( (n=reader.read(buffer)) != null) {
n 不能為 null。
在服務器上循環之后使用 writer.close() 而不是 writer.flush()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.