java常用文件操作

2025-05-09 05:15:59

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、测试

java常用文件操作java常用文件操作

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);

java常用文件操作

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或者百度搜索:

java常用文件操作
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢