1.以IO流的方式拷贝
/**
* 下载图片到工程目录下或者本地
*
* @param dst 图片文件地址
* @param fjname 图片name
* @param fileData 图片输出流本项目orcler数据库是存的二进制数据流可以直接用
*/
public void copyFile(String dst, String fjname, DeferredFileOutputStream fileData) {
//1 提供读入 输出文件(字节流)(可以为txt 或者 图片 视频等)
File file2 = new File(dst + "/" + fjname);
//提供流对象
FileOutputStream fos = null;
try {
if (!file2.exists()) {
file2.createNewFile();
}
fos = new FileOutputStream(file2.getPath());
fileData.writeTo(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
//先关输出
try {
if (fos != null) {
fos.close();
}
if (fileData != null) {
fileData.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.求方式(图片是网络上的图片)
/**
* 下载网络图片到本地
*
* @param src 网络图片地址 本服务器上的需要考虑登录问题 如果可以直接获取到项目库的输入流最好
* @param dst
* @param fjname
*/
public void copyFile(String src, String dst, String fjname) {
//1 提供读入 输出文件(字节流)(可以为txt 或者 图片 视频等)
File file2 = new File(dst + "/" + fjname);
//提供流对象
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(src);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
if (!file2.exists()) {
file2.createNewFile();
}
fos = new FileOutputStream(file2.getPath());
bos = new BufferedOutputStream(fos);
//创建一个Buffer字符串
byte[] buffer = new byte[1024 * 10];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer, 0, 1024 * 10)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
bos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//先关输出
try {
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}