java常用文件操作
1、第一种:根据文件地址判断文件是否存在。1、具体代码如下所示:import java.io.File;import java.io.IOException;public class Test6 { public static void main(String[] args) throws IOException { File file = new File("c:/a/test.txt"); File fileParent = file.getParentFile(); // 如果文件夹存在,删除 if (fileParent.exists() || fileParent.isDirectory()) { System.out.println("存在则执行删除!"); fileParent.delete(); // 删除空文件夹 } else { System.out.println("文件夹不存在,创建!"); fileParent.mkdir(); // 创建文件 file.createNewFile(); } }}2、测试
2、第二种:获取一个文件加下所有文件。1、代码如下所示:import java.io.File;import java.util.ArrayList;import java.util.List;public class Test7 { public static void main(String[] args) { List list = new ArrayList(); print("C:/a", list); // 循环输出list集合 for (Object object : list) { System.out.println(object); } } public static void print(String path, List list) { File file = new File(path); if (!file.isDirectory()) { System.out.println(path + ":不是文件夹"); return; } list.add(file.getPath()); File[] files = file.listFiles(); for (int j = 0; j < files.length; j++) { if (files[j].isFile()) { list.add(files[j].getPath() + files[j].getName()); } else if (files[j].isDirectory()) { print(files[j].getPath(), list); } } }}2、测试功能
3、第三种:将文件转为字节流。1、具体代码如下所示:import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;public class Test8 { public static void main(String[] args) { ByteArrayOutputStream bos = null; BufferedInputStream in = null; try { File file = new File("D:/Documents/Downloads/新建文件夹 (2)/代理合同.pdf"); if (!file.exists()) { throw new FileNotFoundException("file not exists"); } bos = new ByteArrayOutputStream((int) file.length()); in = new BufferedInputStream(new FileInputStream(file)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } System.out.println(bos.toByteArray()); } catch (Exception e) { // TODO: handle exception } }}
4、第四种:将文件字节流下载到前端。1、前端使用window的open方法好处是可以下载异常时可以打印提示信息。var features = 'height租涫疼迟=768, width=1024, top=0, left=0, toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no';window.open("url", "", this.features);2、后台代码,先借助第三步将文件转为字节流(系统调用这样搞,一个系统中字节输出字符流更方便)/** * 输出下载文件 * @param file * @param fileName * @param response * @throws Exception * void Author: Skify Apr 25, 2012 */ public static void download(byte[] file, String fileName, HttpServletResponse response) throws Exception { // 转化为UTF-8避免文件名乱码 fileName = changeFileName(fileName); response.reset(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(response.getOutputStream()); bos.write(file); bos.flush(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { try { if (bos != null) { bos.close(); } } catch (Exception ne) { throw ne; } } } /** * 统一修改文件名 * * @param outputFileName * @return String Author Skify Jun 13, 2011 */ private static String changeFileName(String outputFileName) { int index = outputFileName.lastIndexOf("."); String fileType = ""; if (index != -1) { fileType = outputFileName.substring(index); } Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); return simpleDateFormat.format(date) + fileType; }}3、在页面输出提示信息,后台文件为空或者出现异常时向页面打印信息。PrintWriter pw= response.getWriter();pw.println(msg);
5、第五种:文件拷贝。1、借助于前面第三步先读取文件获取字节流,然后借助于字节流写文件,代码如下所示:(多次执行路径完全相同本次生成的文件会将原文件覆盖)public static void copyFile(byte[] fileByte, String filePath)throws Exception {File file = new File(filePath);FileOutputStream fs = new FileOutputStream(file);BufferedOutputStream bo = new BufferedOutputStream(fs);bo.write(fileByte);bo.close();}2、简单的借助于file流对文件读和写,可以直接参考:https://jingyan.baidu.com/article/f0e83a25544e3c22e5910181.html或者百度搜索: