我正在从 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
连接
提前致谢
最佳答案
您需要:
- 在文件之前发送文件的长度。您可以为此使用
DataOutputStream.writeLong()
,并在接收器处使用DataInputStream.readLong()
。 从接收器的流中准确读取那么多字节:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length : (int)(length-total))) > 0) { out.write(buffer, 0, count); total += count; }
E&OE
Actually I want to reset socket connection
实际上你不想做这样的事情。
关于java - 在套接字上发送和接收文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415934/