servlet操作本地文件汇总: 判断文件是否存在;文件重命名;文件复制; 获取文件属性信息,转成Json对象; 获取指定类型的文件; 查找替换.txt中的文本

2023-04-24,,

 package servlet;

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServlet; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; public class FileActions extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
* 判断文件是否存在
*/
public boolean fileIsExists(File file) {
boolean bool=file.exists();
return bool;
}
/*
* 文件重命名
*/
public boolean fileReName(String filePath, String newName) {
File file=new File(filePath);
boolean isExist=fileIsExists(file);
boolean reName=false;
if(isExist) {
File newFile=new File(file.getParent()+File.separator+newName);
reName=file.renameTo(newFile);
} else {
System.out.println("该文件不存在!");
}
return reName;
}
/*
* 文件复制
*/
public void copyFile(String filePath1,String filePath2) {
File fromFile=new File(filePath1);
File toFiles=new File(filePath2);
boolean isExist1=fileIsExists(fromFile);
if(isExist1) {
try {
boolean isExist2=fileIsExists(toFiles);
if(!isExist2)
toFiles.mkdir();
FileInputStream fis=new FileInputStream(fromFile);
File newFile=new File(toFiles.getPath()+File.separator+fromFile.getName());
FileOutputStream fos=new FileOutputStream(newFile);
int count;
byte[] buffer=new byte[1024];
while((count=fis.read(buffer))!=-1) {
for(int i=0;i<count;i++)
fos.write(buffer[i]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("该文件不存在!");
}
}
/*
* 获取文件信息,转成Json对象
*/
public JSONObject getFileInfo(String filePath) {
JSONObject message=new JSONObject();
File file=new File(filePath);
boolean isExist=fileIsExists(file);
if(isExist) {
if(!file.isFile()) {
message.put("message", "该路径不是文件!");
} else {
message.put("message", "文件存在!");
Map<String, String> fileInfo=new HashMap<String, String>();
try {
fileInfo.put("文件名称", file.getName());
fileInfo.put("文件路径", file.getCanonicalPath());
fileInfo.put("上级目录",file.getParentFile().getParent());
fileInfo.put("隐藏",file.isHidden()?"隐藏":"显示");
fileInfo.put("只读属性", file.canWrite()?"可写":"不可写");
fileInfo.put("最后修改日期", new Date(file.lastModified()).toLocaleString());
fileInfo.put("文件长度", String.format("%#,.2fk", file.length()/1024.0));
JSONObject jsonFileInfo=JSONObject.fromObject(fileInfo);
message.put("属性", jsonFileInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
message.put("message", "该文件不存在!");
}
return message;
}
/*
* 获取指定类型的文件
* 参数1:文件夹路径
* 参数2:指定的文件类型
*/
public JSONArray getFileOneType(String filesPath, String type) {
File[] files=null;
CustomFilter fileFilter=new CustomFilter();
fileFilter.setExtentName(type);
File file=new File(filesPath);
if(file.isDirectory()) {
files=file.listFiles(fileFilter);
}
if(files!=null) {
List<Object[]> fileList=new ArrayList<Object[]>();
for(File f:files) {
Object[] subFile={f.getName(), f.length(), new Date(f.lastModified()).toLocaleString()};
fileList.add(subFile);
}
JSONArray jsonFile=JSONArray.fromObject(fileList);
return jsonFile;
} else {
return null;
}
}
/*
* 查找替换.txt中的文本
* 参数1: 文件路径
* 参数2: 要查找的字符串
* 参数3: 替换字符串
*/
public boolean replaceFileStr(String path, String str, String con) {
try {
FileReader fr=new FileReader(path);
BufferedReader br=new BufferedReader(fr);
char[] data=new char[1024];
int rn=0;
StringBuilder sb=new StringBuilder();
while((rn=fr.read(data))>0) {
String content=String.valueOf(data,0,rn);
sb.append(content);
}
fr.close();
String contentStr=sb.toString().replace(str,con);
FileWriter font=new FileWriter(path);
font.write(contentStr.toCharArray());
font.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} }

以上为servlet层代码,下面为获取指定类型的文件需要用到的CustomFilter类

 package servlet;

 import java.io.File;
import java.io.FileFilter; public class CustomFilter implements FileFilter {
private String extentName; public String getExtentName() {
return extentName;
} public void setExtentName(String extentName) {
this.extentName = extentName;
} @Override
public boolean accept(File pathname) {
if(extentName==null || extentName.isEmpty())
return false;
if(!extentName.startsWith("."))
extentName="."+extentName;
extentName=extentName.toLowerCase();
if(pathname.getName().toLowerCase().endsWith(extentName))
return true;
return false;
} }

servlet操作本地文件汇总: 判断文件是否存在;文件重命名;文件复制; 获取文件属性信息,转成Json对象; 获取指定类型的文件; 查找替换.txt中的文本的相关教程结束。

《servlet操作本地文件汇总: 判断文件是否存在;文件重命名;文件复制; 获取文件属性信息,转成Json对象; 获取指定类型的文件; 查找替换.txt中的文本.doc》

下载本文的Word格式文档,以方便收藏与打印。