服务端开发中,当客户端需要加载服务端发送的图片文件时,需要服务端提供一个下载图片的程序。
下载图片工具类的代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class DownloadImageUtil {
public static byte[] getPicBytes(String goodsPic) {
String picUrl = "D:\\Tomcat6.0\\apache-tomcat-6.0.39\\webapps\\UsedMallMinaServer\\images\\goodsPhotos\\"
+ goodsPic;
// 创建文件
File picFile = new File(picUrl);
// 利用文件流读取图片文件
InputStream is;
byte[] picBytes = null;
try {
is = new FileInputStream(picFile);
int len = (int) picFile.length();
// 创建一个字节数组
picBytes = new byte[len];
int offset = 0;
int numRead = 0;
// 将文件流转换成字节数组
while (offset < picBytes.length
&& ((numRead = is.read(picBytes, offset, len)) >= 0)) {
offset += numRead;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return picBytes;
}
}原文:http://blog.csdn.net/y_chengyong/article/details/37521099