java 接收文件_java – 在socket上发送和接收文件

本文探讨了从Java服务器向Android客户端发送文件时遇到的问题,即读取字节流结束后仍尝试读取的问题。文中提供了具体的代码示例,并讨论了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

实际上,我想重置套接字连接

提前致谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值