java 读取本地文件 增删改查
这里删除不做删除,只是对文件进行重命名,只是物理意义不可见,实际存在
用的jfinal框架

/*** 列出指定路径的文件* @param path 路径* @return 文件集合File[]* */@Overridepublic File[] list(String path){path = path == null ? "./":path;File file=new File(path);if(!file.isDirectory()){throw new WcsmiaRuntimeException("指定路径不是目录!");}return file.listFiles();}/*** 新建文件* @param path 路径* @param name 文件名* @return File 文件*/@Overridepublic File create(String path, String name) {File file=new File(path);if(file.isFile()){throw new WcsmiaRuntimeException("指定目录是一个文件!");}if(file.exists()){file.mkdirs();}file=new File(path+"/"+name);if(!file.exists()){try {file.createNewFile();} catch (IOException e) {throw new WcsmiaRuntimeException("文件创建失败!");}  }return file;}/*** 新建文件* @param path 完整路径含文件名* @return File 文件* @throws IOException */@Overridepublic File create(String path){File file = new File(new File(path).getAbsolutePath());return create(file.getParent(),file.getName());}//public static void main(String[] args){//File create = new FileServiceImp().create("pages");//E:\java\workspace1\com.wcsmia.admin\pages//File create = new FileServiceImp().create("/pages");//E:\pages//File create = new FileServiceImp().create("pages");//E:\pages//File create = new FileServiceImp().create("/index/page/index.html");//E:\index\page//File create = new FileServiceImp().create("src/main/webapp/WEB-INF/pages/index/index3.html");//E:\java\workspace1\com.wcsmia.admin\index\page//System.out.println(create);//}/*** 创建目录* @param path 目录路径* @return file 目录对象*/@Overridepublic File createDirectory(String path) {File dir=new File(path);if(!dir.exists()){dir.mkdir();}return dir;}/*** 复制文件* @param oldsrc 旧文件地址* @param newsrc 新文件地址* @return 复制成功 true*/@Overridepublic boolean copyFile(File oldsrc, File newsrc){if (oldsrc.isDirectory()) { if (!newsrc.exists()) {  newsrc.mkdir();  }String files[] = oldsrc.list(); for (String file : files) {File srcFile = new File(oldsrc,file);File destFile = new File(newsrc,file);//递归复制copyFile(srcFile, destFile);}}else {try {FileInputStream  in = new FileInputStream(oldsrc);OutputStream  out = new FileOutputStream(newsrc);byte[] buffer = new byte[1024];int length;while ((length = in.read(buffer)) > 0) {  out.write(buffer, 0, length);  }in.close(); out.close();} catch (IOException e) {e.printStackTrace();}}return false;}/*** 移动文件* @param file 文件* @param oldpath 旧地址* @param  newpath 新地址* @param cover //若在待转移目录下,已经存在待转移文件* @return boolean 移动成功  true */@Overridepublic boolean move(File file,String newpath,boolean cover) {// TODO Auto-generated method stub/*newpath = newpath.replaceAll("\\", "/");newpath = newpath==null ? "./":newpath;newpath = newpath.endsWith("/") ? newpath+file.getName() : newpath+"/"+file.getName();if(!file.getAbsolutePath().replaceAll("\\", "/").equals(newpath)){File newfile=new File(newpath);if(newfile.exists()&&!cover){//若在待转移目录下,已经存在待转移文件file.renameTo(newfile);return true;}else{throw new WcsmiaRuntimeException("在新目录下已经存在:"+file);}}return true;*/newpath = newpath.replaceAll("\\", "/");File destFloder = new File(newpath);// 检查目标路径是否合法if (destFloder.exists()) {if (destFloder.isFile()) {throw new WcsmiaRuntimeException("目标路径是个文件,请检查目标路径!");}} else {   //判断文件夹是否创建,没有创建则创建新文件夹if (!destFloder.mkdirs()) {throw new WcsmiaRuntimeException("目标文件夹不存在,创建失败!");}}// 检查源文件是否合法if (file.isFile() && file.exists()) {String destinationFile = newpath + "/" + file.getName();if (!file.renameTo(new File(destinationFile))) {throw new WcsmiaRuntimeException("移动文件失败!");}} else {throw new WcsmiaRuntimeException("要备份的文件路径不正确,移动失败!");}return true;}/*public static void main(String[] args) {boolean move = new FileServiceImp().move(new File("\\index\\index.html"),"\\index" ,true);System.out.println(move);}*//*** 重命名* @param file 文件* @param name 新文件名* @return boolean 更改成功  true */@Overridepublic boolean rename(File file, String newname) {if(!file.getName().equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名File newfile=new File(file.getAbsolutePath().replaceAll(file.getName(), newname));if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名throw new WcsmiaRuntimeException(file.getName()+"已经存在!");else{file.renameTo(newfile);return true;}} return false;}/*** 读取文件内容* @param file 文件* @return String 文件内容* @throws IOException */@Overridepublic String read(File file){return read(file, UTF8);}/*** 读取文件内容* @param file 文件* @param encode 编码* @return String 文件内容* @throws IOException */@Overridepublic String read(File file, String encode) {byte[] bs=new byte[(int) file.length()];InputStream stream=null;try {stream = new FileInputStream(file);stream.read(bs);return new String(bs,encode);} catch (IOException e) {throw new WcsmiaRuntimeException("读取文件失败!");}finally {close(stream);}}public static void close(Closeable ...closeables) {if(closeables==null||closeables.length<0)return;try {for(Closeable c:closeables){c.close();}} catch (IOException e) {}}/*** 是否可操作目录* @param path 目录地址* @return 可操作 true*/@Overridepublic boolean filter(String path) {//目前只判断是否在classes目录(项目中类和配置文件存放位置)return new File(path).getAbsolutePath().indexOf("classes")<0;}/*** 更新文件内容* @param file 文件* @param info 文件内容* @return boolean 更改成功  true */@Overridepublic boolean update(File file, String info) {try {if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}file.createNewFile();if(file != null && !"".equals(file.getName())){FileWriter fw = new FileWriter(file, true);fw.write(info);//写入本地文件中fw.flush();fw.close();throw new WcsmiaRuntimeException("执行完毕!");}} catch (IOException e) {e.printStackTrace();}return false;}/*** 更新文件内容* @param file 文件* @param info 文件内容* @param encode 编码* @return boolean 更改成功  true * @throws IOException */@Overridepublic boolean update(File file, String info, String encode) throws IOException {try {if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}file.createNewFile();if(file.getName() != null && !"".equals(file.getName())){FileOutputStream fos = new FileOutputStream(file);OutputStreamWriter osw = new OutputStreamWriter(fos, encode);osw.write(info);osw.flush();osw.close();throw new WcsmiaRuntimeException("执行完毕!");}} catch (IOException e) {e.printStackTrace();}return false;}/*** 删除文件* @param file 文件路径* @return boolean 删除成功  true */@Overridepublic boolean remove(File file) {if(file.exists()&& file.isFile()){//file.delete();String name = file.getName().replace(".html", ""); // 将/换成\rename(file,name+"del.html");return true;}return false;}/*** 重命名目录* @param fromDir 旧目录* @param toDir 新目录(接口)*/public boolean renameDirectory(File file, String toDir) {File from = new File(file.getName());File[] tmp=file.listFiles();if (!from.exists() || !from.isDirectory() || tmp.length==0) {throw new WcsmiaRuntimeException("目录不存在" + file.getName());}File to = new File(toDir);if (from.renameTo(to)){return true;}return false;}/*** 删除目录* @param file 目录对象* @return 删除成功 true*/@Overridepublic boolean removeDirectory(File file) {if(file.exists()){File[] tmp=file.listFiles();String name = file.getName().replace(".html", ""); // 将/换成\if (tmp.length==0) {//file.delete();renameDirectory(file,name+"del");return true;}}return false;}/*** 重命名文件夹* @param f* @throws Exception*/static void changeFile(File f) throws Exception {if (f.isFile()) {//如果是文件,直接更名String path = f.getPath().replace(".html", ""); // 将/换成\  f.renameTo(new File(path + "del.html"));} else {//如果是文件夹,File[] fs = f.listFiles();//得到文件夹下的所有文件列表。System.out.println(fs);for (File f3 : fs)//foreach循环,取文件changeFile(f3);//递归f.renameTo(new File(f.getPath()+ "del"));//循环完后,把该目录更名。}}/*** 删除目录* @param file 目录对象* @param deleteAll 是否删除目录内文件* @return 删除成功 true*/@Overridepublic boolean removeDirectory(File file, boolean deleteAll) {if(file.exists()){File[] tmp=file.listFiles();if (tmp.length == 0) {String name = file.getName().replace(".html", ""); // 将/换成\rename(file,name+"del");} else {if (deleteAll){for(int i=0;i<tmp.length;i++){if(tmp[i].isDirectory()){removeDirectory(file+"\\"+tmp[i].getName(),deleteAll);} else {//tmp[i].delete();String name = tmp[i].getName().replace(".html", ""); // 将/换成\rename(new File(file+"/"+tmp[i].getName()),name+"del.html");}}} else {//如果不删除,文件内所有上移一级/*for(int i=0;i<tmp.length;i++){if(tmp[i].isDirectory()){removeDirectory(file+"/"+tmp[i].getName(),deleteAll);}String name = tmp[i].getName().replace(file.getParent(), "/"); // 将/换成\System.out.println(new File(file+"/"+tmp[i].getName()).getAbsolutePath());System.out.println(file.getParent()+name);rename(new File(file+"/"+tmp[i].getName()),file.getParent()+name);}*/}}String name = file.getName().replace(".html", ""); // 将/换成\rename(file,name+"del");return true;}return false;}/*public static void main(String[] args) {new FileServiceImp().removeDirectory(new File("\\index"), false);}*//*** 删除目录* @param path 目录地址* @return 删除成功 true*/@Overridepublic boolean removeDirectory(String path) {File dir=new File(path);return removeDirectory(dir);}/*** 删除目录* @param path 目录地址* @param deleteAll 是否删除* @return 删除成功 true*/@Overridepublic boolean removeDirectory(String path, boolean deleteAll) {File dir=new File(path);return removeDirectory(dir,deleteAll);}

controller

//目录列表public void list(){String path=!isParaBlank("path") ? getPara("path"):"/";File[] list = fileService.list(path);setAttr("path", new File(path).getAbsolutePath());List<FileBean> fileNames=new ArrayList<>();for(File f:list){fileNames.add(new FileBean(f));}setAttr("files", fileNames);renderTemplate("list.html");}//打开页面public void openhtml(){String path=!isParaBlank("path") ? getPara("path"):"/";String read = fileService.read(new File(path));setAttr("htmlcontent", read);setAttr("path", path);renderTemplate("pageEdit.html");}//删除文件public void delete(){String path=!isParaBlank("path") ? getPara("path"):"/";System.out.println(path+"4567890-");boolean read = fileService.remove(new File(path));renderJson(read);}//重命名文件public void rename(){String path=!isParaBlank("path") ? getPara("path"):"/";boolean remname = fileService.rename(new File(path), "1221.html");renderJson(remname);}//新建文件public void createFilebyPath(){String path=!isParaBlank("path") ? getPara("path"):"/";File create = fileService.create(path, "新建文件夹");renderJson(create);}//删除文件public void remove(){String path=!isParaBlank("path") ? getPara("path"):"/";fileService.remove(new File(path));}//复制文件public void copyFile(){String path=!isParaBlank("path") ? getPara("path"):"/";fileService.copyFile(new File(path).getAbsoluteFile(),new File("F:\\123\\新建文本文档.txt"));}/*public static void main(String[] args) throws IOException {fileService.copyFile(new File("\\index\\122ldel.html").getAbsoluteFile(),new File("F:\\123\\新建文本文档.txt"));}*///更新文件内容public void updateContent(){String path=!isParaBlank("path") ? getPara("path"):"/";String info=getPara("tp.content");fileService.update(new File(path), info);}

具体的controller没写完,但是实现类功能都实现

index页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
This page is list.html12121
<br><ul>
<a href="/createFilebyPath?path=#(path)">新建文件夹</a>
#for(x:files)
#if(!x.getName().contains("del"))#if(x.isDir())<li><a href="/list?path=#(x.getPath())">#(x.getName())</a></li>#else<li>#(x.getName()) <a href="/openhtml?path=#(x.getPath())">打开</a>&nbsp;&nbsp;<a href="/copyFile?path=#(x.getPath())">复制</a>&nbsp;&nbsp;<a href="/delete?path=#(x.getPath())">删除</a>&nbsp;&nbsp;<a href="/rename?path=#(x.getPath())">重命名</a>&nbsp;&nbsp;<a href="/remove?path=#(x.getPath())" >移动</a>&nbsp;&nbsp;</li>#end
#end#end
</ul></body>
</html>

转载,这个人写的也挺不错的
https://www.cnblogs.com/alsf/p/5746480.html
如有不足,请指出,大家一起进步,加油

java File 读取本地文件 增删改查相关推荐

  1. 数据库实验IDEA编程Java程序实现连接数据库以及增删改查JDBC

    IDEA编程Java程序实现连接数据库以及增删改查JDBC IDEA的mysql环境配置建议参考该博客:戳我 我用的是java11和此博客的配置略有出入,不过一般的问题都可以百度解决 这是我实验用的数 ...

  2. java对数据库的增删改查_在java中对数据库进行增删改查

    代码区域: package com.oracle.jdbc.demo1; import java.sql.Connection; import java.sql.DriverManager; impo ...

  3. iOS开发-plist文件增删改查

    plist第一次看到这个后缀名文件的时候感觉怪怪的,不过接触久了也就习以为常了,plist是Property List的简称可以理解成属性列表文件,主要用来存储串行化后的对象的文件.扩展名为.plis ...

  4. Java Web(十) JDBC的增删改查,C3P0等连接池,dbutils框架的使用

    前面做了一个非常垃圾的小demo,真的无法直面它,菜的抠脚啊,真的菜,好好努力把.菜鸡. --WZY 一.JDBC是什么? Java Data Base Connectivity,java数据库连接, ...

  5. java springboot+mybaits 实现数据库增删改查案例

    springboot是java中最实用,当前也是最流行的框架,mybaits对应dao层.想要做项目springboot和mybaits是必须的.今天就教大家怎么简单搭建一个用springboot的增 ...

  6. Java操作Mongodb数据(增删改查聚合查询)

    文章目录 一.Java操作MongoDB 二.使用步骤 1.基础配置 2.实体类 3.MongoDB表数据 3.增删改查聚合查询 总结 一.Java操作MongoDB 上一篇文章介绍了,如何在本地使用 ...

  7. ElasticSearch初体验之使用Java进行最基本的增删改查

    好久没写博文了, 最近项目中使用到了ElaticSearch相关的一些内容, 刚好自己也来做个总结. 现在自己也只能算得上入门, 总结下自己在工作中使用Java操作ES的一些小经验吧. 本文总共分为三 ...

  8. java indexof方法_【3-14】Java中集合类list的增删改查

    Hello,大家好,我是大家最亲爱的siki老师,每天都会在这里为大家带来一个Java语法中有趣的知识点,Q群175158287,欢迎同大家多多交流哈! 今天给大家带来的是Java中list类的使用, ...

  9. 双表查询java代码_多表增删改查

    [java]代码库package com.ww.service; import java.lang.reflect.Array; import java.sql.Connection; import ...

最新文章

  1. 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json
  2. linux压缩和解压缩类命令|--zip/unzip指令
  3. (转)linux下vi编辑器编写C语言的配置
  4. Activiti7整合SpringBoot
  5. 建模没有用『灵敏度分析』,一半儿的报名费已经飞了
  6. QQ小程序激励广告接入与使用
  7. 除了提升听感,鲸云音效对网易云音乐还意味着什么?
  8. 微信显示android23,微信7.0.23内测版发布 新增6个新功能
  9. linux 终端分屏工具 tmux
  10. 七类人不适合学计算机,考研女生谨慎报考!这几个专业可能真的不适合!
  11. JAVA猎才优秀博主分享
  12. 凯捷面试(2):JavaWeb、框架
  13. N9344C安捷伦频谱分析仪
  14. Hadoop高手之路5-MapRreduce
  15. P7788 [COCI2016-2017#6] Savrsen
  16. 电信、网通、铁通各地DNS
  17. 输入月份号并输出英文月份名
  18. svn提交数据失败的原因和解决办法
  19. springcloud(11)Alibaba-AHAS 限流方式
  20. c语言 图片漫画效果,【教程】教你用手机修出动漫风格人像照片

热门文章

  1. 计算机组成二进制除法,计算机组成原理:3.4.1 定点原码 除法器
  2. 精通Matlab数字图像处理与识别nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;
  3. 腾讯云-即时通讯 IM
  4. 谭浩强C++ 第八章
  5. C#实现土豆优酷等网站视频的缩略图
  6. uva 10306 e-coins【dp】
  7. The Sultan's Successors (八皇后)
  8. 如何在应用中打开系统播放器
  9. 1-计算机是如何工作的?
  10. P5405 [CTS2019]氪金手游 【数学概率+树形dp】