@Test
public void TestChiPan() throws IOException {
// File file=new File("G:\\timg.jpg");
//File file=new File("C:\\Users\\win10\\Desktop\\新建文件夹\\答辩PPT.pptx");
File file=new File("wenjian/1.jpg");
InputStream inputStream=new FileInputStream(file);
byte[] pic=new byte[inputStream.available()];
inputStream.read(pic);
inputStream.close();
File file2 = new File("wenjian/3.jpg");
FileOutputStream outputStream = new FileOutputStream(file2);
outputStream.write(pic);
outputStream.close();
}
服务器返回文件
@RequestMapping("/downLoadFile")
public void DownLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName=request.getParameter("fileName");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
System.out.println(fileName);
//FileInputStream in = new FileInputStream("G:\\"+fileName);
FileInputStream in = new FileInputStream("/"+fileName);
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode("fileName", "utf-8"));
OutputStream out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件流
in.close();
// 关闭输出流
out.close();
}
android 从服务器下载文件
@Test
public void TestDownLoadFile() throws IOException {
URL url = new URL("http://localhost/downLoadFile/downLoadFile?fileName=timg.jpg");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);
con.setConnectTimeout(5000);
con.setRequestProperty("Charset", "UTF-8");
con.setRequestMethod("GET");
if (con.getResponseCode() == 200) {
InputStream is = con.getInputStream();//获取输入流
FileOutputStream fileOutputStream = null;//文件输出流
if (is != null) {
fileOutputStream = new FileOutputStream("G:\\TestMysql\\tig.jpg");//指定文件保存路径,代码看下一步
byte[] buf = new byte[1024];
int ch;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
System.out.println("写文件");
}
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
}