gpt4 book ai didi

java - 在套接字上发送和接收文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:28:29 25 4
gpt4 key购买 nike

我正在从 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连接

提前致谢

最佳答案

您需要:

  1. 在文件之前发送文件的长度。您可以为此使用 DataOutputStream.writeLong() ,并在接收器处使用 DataInputStream.readLong()
  2. 从接收器的流中准确读取那么多字节:

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com