java 读取本地文件 增删改查
这里删除不做删除,只是对文件进行重命名,只是物理意义不可见,实际存在
用的jfinal框架
/**
* 列出指定路径的文件
* @param path 路径
* @return 文件集合File[]
*
*/
@Override
public 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 文件
*/
@Override
public 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
*/
@Override
public 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 目录对象
*/
@Override
public File createDirectory(String path) {
File dir=new File(path);
if(!dir.exists()){
dir.mkdir();
}
return dir;
}
/**
* 复制文件
* @param oldsrc 旧文件地址
* @param newsrc 新文件地址
* @return 复制成功 true
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public String read(File file){
return read(file, UTF8);
}
/**
* 读取文件内容
* @param file 文件
* @param encode 编码
* @return String 文件内容
* @throws IOException
*/
@Override
public 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
*/
@Override
public boolean filter(String path) {
//目前只判断是否在classes目录(项目中类和配置文件存放位置)
return new File(path).getAbsolutePath().indexOf("classes")<0;
}
/**
* 更新文件内容
* @param file 文件
* @param info 文件内容
* @return boolean 更改成功 true
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public 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
*/
@Override
public boolean removeDirectory(String path) {
File dir=new File(path);
return removeDirectory(dir);
}
/**
* 删除目录
* @param path 目录地址
* @param deleteAll 是否删除
* @return 删除成功 true
*/
@Override
public 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>
<a href="/copyFile?path=#(x.getPath())">复制</a>
<a href="/delete?path=#(x.getPath())">删除</a>
<a href="/rename?path=#(x.getPath())">重命名</a>
<a href="/remove?path=#(x.getPath())" >移动</a>
</li>
#end
#end
#end
</ul>
</body>
</html>
转载,这个人写的也挺不错的
https://www.cnblogs.com/alsf/p/5746480.html
如有不足,请指出,大家一起进步,加油