java常用文件操作

 时间:2024-10-16 02:31:08

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常用文件操作
  • jmeter性能工具怎么脚本中添加集合点同步计时器
  • Ubuntu16.04(Linux)安装PyCharm社区开源版
  • Eclipse离线安装Maven插件
  • 怎样使用svn/svn使用方法/教程/:[3]之修改篇
  • jquery如何查找所有a标签中属性为指定值的对象
  • 热门搜索
    治疗鸡眼的最佳方法 羊腿怎么做好吃 成语大全 后脑勺疼怎么回事 设计方法 蒸鸡蛋糕的家常做法 年轻人血压高怎么办 蒸肉的家常做法 酱豆腐的家常做法 牛排怎么做好吃