整理一些文件操作的java代码,可直接使用。如果遇到用到的再进行补充。
创建文件
**
* 创建文件
* @param fileName 文件名称
* @param filecontent 文件内容
* @return 是否创建成功,成功则返回true
*/
public static boolean createFile(String path,String fileName,String filecontent){
Boolean bool = false;
File file = new File(path+fileName);
try {
//如果文件不存在,则创建新的文件
if(!file.exists()){
if(!file.createNewFile())
{
logger.error("文件创建失败!");
return false;
}
bool = true;
logger.info("success create file,the file is "+path+fileName);
//创建文件成功后,写入内容到文件里
}
writeFileContent(path+fileName, filecontent);
} catch (Exception e) {
logger.error(e);
}
return bool;
}
/**
* 向文件中写入内容
* @param filepath 文件路径与名称
* @param newstr 写入的内容
* @return
* @throws IOException
*/
public static boolean writeFileContent(String filepath,String newstr) throws IOException{
Boolean bool = false;
String filein = newstr+"\r\n";//新写入的行,换行
String temp = "";
File file = new File(filepath);//文件路径(包括文件名称)
try(FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos)){
//将文件读入输入流
StringBuilder buffer = new StringBuilder();
//文件原有内容
while((temp=br.readLine())!=null){
buffer.append(temp);
// 行与行之间的分隔符 相当于“\n”
buffer = buffer.append(System.getProperty("line.separator"));
}
buffer.append(filein);
pw.write(buffer.toString().toCharArray());
pw.flush();
bool = true;
} catch (Exception e) {
logger.error(e);
}
return bool;
}
xml文件操作
public static void getconfXMLinfo(String path ) throws DocumentException{
SAXReader sax=new SAXReader();//创建一个SAXReader对象
File xmlFile=new File(path);//根据指定的路径创建file对象
Document document=sax.read(xmlFile);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
getNodes(root);//从根节点开始遍历所有节点
}
/***
*递归遍历当前节点所有的子节点
*/
public static void getNodes(Element node){
//递归遍历当前节点所有的子节点
@SuppressWarnings("unchecked")
List<Element> listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
getNodes(e);//递归
}
}
解压文件
/**
* 解压缩JAR包
* @param fileName 文件名
* @param outputPath 解压输出路径
* @throws IOException IO异常
*/
private static void decompress(String fileName, String outputPath) throws IOException{
if (!outputPath.endsWith(File.separator)) {
outputPath += File.separator;
}
JarFile jf = new JarFile(fileName);
for (Enumeration e = jf.entries(); e.hasMoreElements();)
{
JarEntry je = (JarEntry) e.nextElement();
String outFileName = outputPath + je.getName();
File f = new File(outFileName);
logger.info(f.getAbsolutePath());
//创建该路径的目录和所有父目录
makeSupDir(outFileName);
//如果是目录,则直接进入下一个循环
if(f.isDirectory())
{
continue;
}
InputStream in = null;
OutputStream out = null;
try
{
in = jf.getInputStream(je);
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buffer = new byte[2048];
int nBytes = 0;
while ((nBytes = in.read(buffer)) > 0)
{
out.write(buffer, 0, nBytes);
}
}catch (IOException ioe)
{
throw ioe;
} finally
{
try
{
if (null != out)
{
out.flush();
out.close();
}
} catch (IOException ioe)
{
throw ioe;
}
finally
{
if (null != in)
{
in.close();
}
}
}
}
}
删除文件/文件夹
/**
** 删除所有文件
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
flag=temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
}
//删除文件夹
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
java.nio.file.Files.delete(java.nio.file.Paths.get(folderPath));
} catch (Exception e) {
logger.error(e);
}
}
文件拷贝
//拷贝文件
public static void copyFile(String path, String copyPath) {
File filePath = new File(path);
if(filePath.isDirectory()){
File[] list = filePath.listFiles();
new File(copyPath).mkdir();
for(int i=0; i<list.length; i++){
String newPath = path + File.separator + list[i].getName();
String newCopyPath = copyPath + File.separator + list[i].getName();
File newFile = new File(copyPath);
if(!newFile.exists()){
newFile.mkdir();
}
copyFile(newPath, newCopyPath);
}
}else if(filePath.isFile()){
try(
DataInputStream read = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
DataOutputStream write = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(copyPath)))
){
byte [] buf = new byte[1024*512];
int n =read.read(buf);
while( n!= -1){
write.write(buf,0,n);
n =read.read(buf);
}
write.flush();
}
catch (IOException e){
logger.error(e.getMessage(),e);
}
}else{
logger.info("请输入正确的文件名或路径名");
}
}
读取文件某个字符并替换
/**
*
* @param filePath 文件位置
* @param oldString 需要匹配行数的字符
* @param newString 替换新的字符 (全部替换)
*/
public static void readFileForReplace(String filePath, String oldString, String newString){
BufferedReader br = null;
BufferedWriter bw = null;
String line = null;
StringBuffer bufAll = new StringBuffer();// 保存修改过后的所有内容
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
while ((line = br.readLine()) != null) {
StringBuffer buf = new StringBuffer();
// 修改内容核心代码
if (line.startsWith(oldString)) {//判断条件根据自己的要求修改
buf.append(line);
int indexOf = line.indexOf(oldString);
buf.replace(indexOf, indexOf + oldString.length(), newString);// 修改内容
buf.append(System.getProperty("line.separator"));// 添加换行
bufAll.append(buf);
} else {
buf.append(line);
buf.append(System.getProperty("line.separator"));
bufAll.append(buf);
}
}
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
bw.write(bufAll.toString());
bw.flush();
} catch (Exception e) {
logger.error("修改Jboss的run.bat文件执行出现了异常!");
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
br = null;
}
}
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
bw = null;
}
}
}
}