【发布时间】:2013-09-03 18:36:37
【问题描述】:
我创建了一个应用程序,它通过套接字编程将图像从服务器(桌面)发送到客户端(android)............问题是我在客户端获取文件(android),但没有内容。
谁能告诉我是什么问题
客户端(Android)
DataInputStream dis=new DataInputStream(socket.getInputStream());
receiveFile(dis); // call method receiveFile()
public Bitmap receiveFile(InputStream is) throws Exception{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.png";
String imageInSD = baseDir + File.separator + fileName;
System.out.println("FILE----------------->"+imageInSD);
int filesize=6022386;
int bytesRead;
int current = 0;
byte [] data = new byte [filesize];
FileOutputStream fos = new FileOutputStream(imageInSD);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(data,0,data.length);
current = bytesRead;
int index = 0;
while (index < filesize)
{
bytesRead = is.read(data, index, filesize - index);
if (bytesRead < 0)
{
throw new IOException("Insufficient data in stream");
}
index += filesize;
}
bos.write(data, 0 , current);
bos.flush();
bos.close();
return null;
}
服务器(桌面)
send(socket.getOutputStream()); // call method send()
public void send(OutputStream os) throws Exception{
// sendfile
File myFile = new File ("C:/div.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();
}
【问题讨论】:
-
只是滚动浏览,但您在
is.read(data,0,data.length)行中读取,但不使用其中读取的字节数(不应该进入index)? -
问题可能出在
index +=filesize;应该是index +=bytesread;并且还要考虑之前的评论。