我正在尝试将图片从 pc 发送到 android 手机我在发送图片时遇到问题。我在此处发布发送图片的 java 应用程序的代码。
public void send(OutputStream os) throws Exception{
// sendfile
File myFile = new File ("E:\\a.png");
System.out.println("the file is read");
byte [] mybytearray = new byte [(int)myFile.length()+1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
上面的代码只是在端口上写文件。
这是实际接收该文件的android代码。循环开始并且不退出。连接到端口是正确的,我可以发送和接收字符串
public Bitmap receiveFile(InputStream is) throws Exception{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.png";
String imageInSD = baseDir + File.separator + fileName;
int filesize=6022386;
int bytesRead;
int current = 0;
byte [] mybytearray = new byte [filesize];
FileOutputStream fos = new FileOutputStream(imageInSD);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead != -1);
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
return null;
}
请建议任何其他分享图片的方式