【发布时间】:2014-07-31 18:44:19
【问题描述】:
我正在从 java 服务器向远程 Android 客户端发送文件。我使用输出流写入字节。在读取这些字节时,read() 方法会在流结束后继续尝试读取字节。如果我在服务器端关闭outputstream,读取操作工作正常。但是我必须再次在同一个套接字上写入文件所以无法关闭输出流任何解决方案?
注意:我的代码适用于共享单个文件
编写文件的代码
public static void writefile(String IP, String filepath, int port, OutputStream out) throws IOException {
ByteFileConversion bfc = new ByteFileConversion();
byte[] file = bfc.FileToByteConversion(filepath);
out.write(file, 0, file.length);
out.close(); // i donot want to close this and how can I tell reading side that stream is ended.
System.out.println("WRITTEN");
}
这是我在 Android 上阅读的文件:
public Bitmap fileReceived(InputStream is) {
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
// System.out.println(imageInSD);
if (is != null) {
FileOutputStream fos = null;
OutputStream bos = null;
try {
bos = new FileOutputStream(imageInSD);
byte[] aByte = new byte[1024];
int bytesRead;
int index = 0;
DataInputStream dis = new DataInputStream(is);
while ((bytesRead = is.read(aByte)) > 0) {
index = bytesRead + index;
bos.write(aByte, 0, bytesRead);
// index = index+ bytesRead;
System.out.println("Loop" + aByte + " byte read are " + bytesRead + "whree index =" + index);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "out of loop");
java.io.FileInputStream in = new FileInputStream(imageInSD);
bitmap = BitmapFactory.decodeStream(in);
bitmap = BitmapFactory.decodeFile(imageInSD);
Log.i("IMSERVICE", "saved");
// if (bitmap != null)
// System.out.println("bitmap is "+ bitmap.toString());
} catch (IOException ex) {
// Do exception handling
// Log.i("IMSERVICE", "exception ");
System.out.println("ex");
}
}
return bitmap;
}
其实我想重置socket连接
提前致谢
【问题讨论】:
-
我的代码正确读写文件。我想再次使用即将写入另一个文件的输出流。但是由于输出流很接近所以我不能这样做。如果我不关闭输出流,另一侧的读取操作会卡在继续阅读
-
@RodAlgonquin TCP 无法发送和接收单个数据包。它是一个字节流。您必须添加自己的元数据。
-
@EJP 我明白了,但这并不是他的问题,他希望按照我在下面的建议打开他的输出,但我不知道他们为什么不赞成。
-
@Rod_Algonquin 这正是他的问题。他需要在第一个文件结束后停止阅读,目前除了套接字的流结束之外,他没有办法告诉文件结束。请参阅我的答案 fpr 解决方案。仅仅将阻塞行为移动到一个单独的线程中根本无法解决问题。
标签: java android sockets network-programming