我正在从java服务器向远程Android客户端发送文件.我使用outputstream写字节.在读取这些字节时,read()方法会在流结束后继续尝试读取字节.如果我在服务器端关闭输出流,则读 *** 作工作罚款.但我必须再次在同一个套接字上写文件,所以无法关闭输出流的任何解决方案?
注意:我的代码适用于共享单个文件
编写文件的代码
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;}
实际上,我想重置套接字连接
提前致谢
解决方法:
你需要:
>在文件前发送文件的长度.您可以使用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 – 在socket上发送和接收文件全部内容,希望文章能够帮你解决java – 在socket上发送和接收文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)