常用的文件操作:包括文件拷贝、HTTP方式拷贝、文件下载等。
1.创建文件夹
/** * 创建文件夹 * @filePath:路径 */ public void MakeFolder(String folderPath){ File file =new File(folderPath); //如果文件夹不存在则创建 if(!file.exists() && !file.isDirectory()) { System.out.println("//不存在"); file.mkdirs(); }else { System.out.println("//目录存在"); } } //使用示例 MakeFolder("E:\Java\newFile");
2.创建文件
/** * 创建文件 * @folderPath:路径 */ public void MakeFile(String filePath){ File file=new File(filePath); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //使用示例 MakeFile("E:\Java\newFile\helloworld.txt");
3.本地拷贝文件
/** * 拷贝文件 * @sourcePath:源文件路径 * @destPath:目标文件路径 * @folderName:文件夹路径 */ public void copyFile(String sourcePath, String destPath,String folderName) throws Exception { File source = new File(sourcePath); if(!folderName.equals("")){ File folder = new File(folderName); //文件夹不存在,创建 if(!folder.exists() && !folder.isDirectory()) { folder.mkdirs(); } } File dest = new File(destPath); if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(dest); FileChannel sourceCh = fis.getChannel(); FileChannel destCh = fos.getChannel(); MappedByteBuffer mbb = sourceCh.map(FileChannel.MapMode.READ_ONLY, 0,sourceCh.size()); destCh.write(mbb); sourceCh.close(); destCh.close(); }
4.下载HTTP资源文件到服务器硬盘路径
/** * HTTP方式下载文件 * @url:源文件远程地址 * @dir:下载地址目录 * @return:1成功 0:失败 */ public int downloadFromUrl(String url,String dir) { try { URL httpurl = new URL(url); File f = new File(dir); FileUtils.copyURLToFile(httpurl, f); } catch (Exception e) { e.printStackTrace(); return 0; } return 1; }
5.用户下载服务器资源文件
/** * 下载服务器文件 * @fullfilepath:文件所在硬盘的真实路径 * @downloadfilename:下载的文件命名 */ public void DownloadFile(String fullfilepath,String downloadfilename,HttpServletResponse response){ try{ /*读取文件*/ File file = new File(fullfilepath); /*如果文件存在*/ if (file.exists()) { downloadfilename = URLEncoder.encode(downloadfilename, enc); response.reset(); response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename="" + downloadfilename + """); int fileLength = (int) file.length(); response.setContentLength(fileLength); /*如果文件长度大于0*/ if (fileLength != 0) { /*创建输入流*/ InputStream inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /*创建输出流*/ ServletOutputStream servletOS = response.getOutputStream(); int readLength; while (((readLength = inStream.read(buf)) != -1)) { servletOS.write(buf, 0, readLength); } inStream.close(); servletOS.flush(); servletOS.close(); } }else{ System.out.println("Error: can't find the file "+filename); } }catch(Exception e){ System.out.println("文件下载出错!"); } }