java 文件操作工具类

来源:互联网 发布:淘宝拍摄衣服怎么布光 编辑:程序博客网 时间:2024/05/22 10:33

1.  获取绝对路径

前一段做个程序,遇到了这样一个问题,想利用相对路径删掉一个文件(实际存在的),老是删不掉. 真是急人呀,最后让我费了好大力气才算把它解决掉,问题不防跟大家说说,万一遇到这样的问题,就不用再费劲了!

情况是这样的:我的Tomcat装在了c盘,而我的虚拟目录设在了E:/work下, 我在E:/work/test/image下有个图片,test.gif 我想通过程序删掉它,但他的绝对路径不确定(为了考虑到程序以后的移植,绝对路径是不确定的)。

假设del.jsp文件在e:/work/test 下,用下面的程序好像可以删掉:

<!--原始的del.jsp源文件-->
<%@ page contentType="text/html; charset=GBK" errorPage="" %>
<%request.setCharacterEncoding("GBK");%>
<%@ page language="java" import="java.sql.*" import="java.util.*" import ="java.text.*" import="java.io.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>删除成功页面</title>
</head>
<body>
File f=new File("/image/",test.gif);
boolean a=f.delete();
out.print("a="+a);
</body>
</html>

但事实上不行,你会发现a=false;

这就需要获取其绝对路径, 我们用java程序来做一个专门来获取绝对路径的javaBean(path_test.java)就可以了。

path_test.java的代码如下:
package pathtest;
import java.io.*;
import javax.servlet.*;
import javax.servlet.jsp.PageContext;//导入PageContext类,不要忘了
public class path_test
{

protected ServletContext m_application;
private boolean m_denyPhysicalPath;
public path_test()
{

}
public final void initialize(PageContext pageContext)
throws ServletException
{
m_application = pageContext.getServletContext();

}

public String getPhysicalPath(String filePathName, int option)
throws IOException
{
String path = new String();
String fileName = new String();
String fileSeparator = new String();
boolean isPhysical = false;
fileSeparator=System.getProperty("file.separator");
if(filePathName == null)
throw new IllegalArgumentException("There is no specified destination file (1140).");
if(filePathName.equals(""))
throw new IllegalArgumentException("There is no specified destination file (1140).");
if(filePathName.lastIndexOf("\\") >= 0)
{
path = filePathName.substring(0, filePathName.lastIndexOf("\\"));
fileName = filePathName.substring(filePathName.lastIndexOf("\\") + 1);
}
if(filePathName.lastIndexOf("/") >= 0)
{
path = filePathName.substring(0, filePathName.lastIndexOf("/"));
fileName = filePathName.substring(filePathName.lastIndexOf("/") + 1);
}
path = path.length() != 0 ? path : "/";
java.io.File physicalPath = new java.io.File(path);
if(physicalPath.exists())
isPhysical = true;
if(option == 0)
{
if(isVirtual(path))
{
path = m_application.getRealPath(path);
if(path.endsWith(fileSeparator))
path = path + fileName;
else
path = String.valueOf((new StringBuffer(String.valueOf(path))).append(fileSeparator).append(fileName));
return path;
}
if(isPhysical)
{
if(m_denyPhysicalPath)
throw new IllegalArgumentException("Physical path is denied (1125).");
else
return filePathName;
} else
{
throw new IllegalArgumentException("This path does not exist (1135).");
}
}
if(option == 1)
{
if(isVirtual(path))
{
path = m_application.getRealPath(path);
if(path.endsWith(fileSeparator))
path = path + fileName;
else
path = String.valueOf((new StringBuffer(String.valueOf(path))).append(fileSeparator).append(fileName));
return path;
}
if(isPhysical)
throw new IllegalArgumentException("The path is not a virtual path.");
else
throw new IllegalArgumentException("This path does not exist (1135).");
}
if(option == 2)
{
if(isPhysical)
if(m_denyPhysicalPath)
throw new IllegalArgumentException("Physical path is denied (1125).");
else
return filePathName;
if(isVirtual(path))
throw new IllegalArgumentException("The path is not a physical path.");
else
throw new IllegalArgumentException("This path does not exist (1135).");
}

else
{
return null;
}

}
private boolean isVirtual(String pathName) //判断是否是虚拟路径
{
if(m_application.getRealPath(pathName) != null)
{
java.io.File virtualFile = new java.io.File(m_application.getRealPath(pathName));
return virtualFile.exists();
}

else
{
return false;
}
}

}

对path_test.java编译后,得到包pathtest,里面有path_test.class类,

把整个包放到虚拟目录的classes下,然后再把del.jsp文件改成如下程序,一切都OK了!

<!--改后的del.jsp的源文件-->
<%@ page contentType="text/html; charset=GBK" errorPage="" %>
<%request.setCharacterEncoding("GBK");%>
<%@ page language="java" import="java.sql.*" import="java.util.*" import ="java.text.*" import="java.io.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>删除成功页面</title>
</head>
<body>
<jsp:useBean id="pathtest" scope="page" class="pathtest.path_test" />
pathtest.initialize(pageContext);//初始化
String dir1=pathtest.getPhysicalPath("/test/image/",0);//传参数
out.print(dir1);//输出的是绝对路径
File file=new File(dir1,"test.gif");//生成文件对象
boolean a=file.delete();
out.print("a="+a);
</body">
</html>

此时a=true;表示删除成功!

到此为止,问题全部搞定。

2.  文件操作工具类

package com.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.swing.text.html.HTMLDocument.HTMLReader.FormAction;

/**
 *
 * 功能描述:
 *
 * @author Administrator
 * @Date Jul 19, 2008
 * @Time 9:46:11 AM
 * @version 1.0
 */
public class FileUtil {

 /**
  * 功能描述:列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
  *
  * @param path
  *            文件夹
  */
 public static void list(File path) {
  if (!path.exists()) {
   System.out.println("文件名称不存在!");
  } else {
   if (path.isFile()) {
    if (path.getName().toLowerCase().endsWith(".pdf")
      || path.getName().toLowerCase().endsWith(".doc")
      || path.getName().toLowerCase().endsWith(".chm")
      || path.getName().toLowerCase().endsWith(".html")
      || path.getName().toLowerCase().endsWith(".htm")) {// 文件格式
     System.out.println(path);
     System.out.println(path.getName());
    }
   } else {
    File[] files = path.listFiles();
    for (int i = 0; i < files.length; i++) {
     list(files[i]);
    }
   }
  }
 }

 /**
  * 功能描述:拷贝一个目录或者文件到指定路径下,即把源文件拷贝到目标文件路径下
  *
  * @param source
  *            源文件
  * @param target
  *            目标文件路径
  * @return void
  */
 public static void copy(File source, File target) {
  File tarpath = new File(target, source.getName());
  if (source.isDirectory()) {
   tarpath.mkdir();
   File[] dir = source.listFiles();
   for (int i = 0; i < dir.length; i++) {
    copy(dir[i], tarpath);
   }
  } else {
   try {
    InputStream is = new FileInputStream(source); // 用于读取文件的原始字节流
    OutputStream os = new FileOutputStream(tarpath); // 用于写入文件的原始字节的流
    byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
    int len = 0;
    while ((len = is.read(buf)) != -1) {
     os.write(buf, 0, len);
    }
    is.close();
    os.close();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
//  File file = new File("D:\\个人资料\\MySQL 5");
//  list(file);
  Date myDate = new Date();
  DateFormat df = DateFormat.getDateInstance();
  System.out.println(df.format(myDate));
 }

}

3. 文件压缩,解压,删除,拷贝

此类包含利用JAVA进行文件的压缩,解压,删除,拷贝操作。部分代码总结了网上的代码,并修正了很多BUG,例如压缩中文问题,压缩文件中多余空文件问题。

    注意:此类中用到的压缩类ZipEntry等都来自于org.apache.tools包而非java.util。此包在ant.jar中有。

  /*
     * Version information

     *

     * Date:2008-6-26

     *

     * Copyright (C) 2008 Chris.Tu
     */

 

    package test;


    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.util.Enumeration;

 

    import org.apache.tools.zip.ZipEntry;

    import org.apache.tools.zip.ZipFile;

    import org.apache.tools.zip.ZipOutputStream;

    import org.slf4j.Logger;

    import org.slf4j.LoggerFactory;

 

    /**

     * java文件操作工具类

     * @author Chris

     * @version 2008-6-26

     */

    public class FileUtil {

 

        protected static Logger log = LoggerFactory.getLogger(FileUtil.class);

 

        /**

         * 压缩文件

         * @param inputFileName 要压缩的文件或文件夹路径,例如:c:\\a.txt,c:\\a\

         * @param outputFileName 输出zip文件的路径,例如:c:\\a.zip

         */

        public static void zip(String inputFileName, String outputFileName) throws Exception {

 

            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));

            zip(out, new File(inputFileName), "");

            log.debug("压缩完成!");

            out.closeEntry();

            out.close();

        }

/**

         * 压缩文件

         * @param out org.apache.tools.zip.ZipOutputStream

         * @param file 待压缩的文件

         * @param base 压缩的根目录

         */

        private static void zip(ZipOutputStream out, File file, String base) throws Exception {

 

            if (file.isDirectory()) {

                File[] fl = file.listFiles();

                base = base.length() == 0 ? "" : base + File.separator;

                for (int i = 0; i < fl.length; i++) {

                    zip(out, fl[i], base + fl[i].getName());

                }

            } else {

                out.putNextEntry(new ZipEntry(base));

                log.debug("添加压缩文件:" + base);

                FileInputStream in = new FileInputStream(file);

                int b;

                while ((b = in.read()) != -1) {

                    out.write(b);

                }

                in.close();

            }

        }

 

        /**

         * 解压zip文件

         * @param zipFileName 待解压的zip文件路径,例如:c:\\a.zip

         * @param outputDirectory 解压目标文件夹,例如:c:\\a\

         */

        public static void unZip(String zipFileName, String outputDirectory) throws Exception {

 

            ZipFile zipFile = new ZipFile(zipFileName);

            try {

                Enumeration<?> e = zipFile.getEntries();

                ZipEntry zipEntry = null;

                createDirectory(outputDirectory, "");

                while (e.hasMoreElements()) {

                    zipEntry = (ZipEntry) e.nextElement();

                    log.debug("解压:" + zipEntry.getName());

                    if (zipEntry.isDirectory()) {

                        String name = zipEntry.getName();

                        name = name.substring(0, name.length() - 1);

                        File f = new File(outputDirectory + File.separator + name);

                        f.mkdir();

                        log.debug("创建目录:" + outputDirectory + File.separator + name);

                    } else {

                        String fileName = zipEntry.getName();

                        fileName = fileName.replace('\\', '/');

                        if (fileName.indexOf("/") != -1) {

                            createDirectory(outputDirectory, fileName.substring(0, fileName.lastIndexOf("/")));

                            fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());

                        }

 

                        File f = new File(outputDirectory + File.separator + zipEntry.getName());

 

                        f.createNewFile();

                        InputStream in = zipFile.getInputStream(zipEntry);

                        FileOutputStream out = new FileOutputStream(f);

 

                        byte[] by = new byte[1024];

                        int c;

                        while ((c = in.read(by)) != -1) {

                            out.write(by, 0, c);

                        }

                        in.close();

                        out.close();

                    }

                }

            } catch (Exception ex) {

                System.out.println(ex.getMessage());

            } finally {

                zipFile.close();

                log.debug("解压完成!");

            }

 

        }

 private static void createDirectory(String directory, String subDirectory) {

 

            String dir[];

            File fl = new File(directory);

            try {

                if (subDirectory == "" && fl.exists() != true) {

                    fl.mkdir();

                } else if (subDirectory != "") {

                    dir = subDirectory.replace('\\', '/').split("/");

                    for (int i = 0; i < dir.length; i++) {

                        File subFile = new File(directory + File.separator + dir[i]);

                        if (subFile.exists() == false)

                            subFile.mkdir();

                        directory += File.separator + dir[i];

                    }

                }

            } catch (Exception ex) {

                System.out.println(ex.getMessage());

            }

        }

 

        /**

         * 拷贝文件夹中的所有文件到另外一个文件夹

         * @param srcDirector 源文件夹

         * @param desDirector 目标文件夹

         */

        public static void copyFileWithDirector(String srcDirector, String desDirector) throws IOException {

 

            (new File(desDirector)).mkdirs();

            File[] file = (new File(srcDirector)).listFiles();

            for (int i = 0; i < file.length; i++) {

                if (file[i].isFile()) {

                    log.debug("拷贝:" + file[i].getAbsolutePath() + "-->" + desDirector + "/" + file[i].getName());

                    FileInputStream input = new FileInputStream(file[i]);

                    FileOutputStream output = new FileOutputStream(desDirector + "/" + file[i].getName());

                    byte[] b = new byte[1024 * 5];

                    int len;

                    while ((len = input.read(b)) != -1) {

                        output.write(b, 0, len);

                    }

                    output.flush();

                    output.close();

                    input.close();

                }

                if (file[i].isDirectory()) {

                    log.debug("拷贝:" + file[i].getAbsolutePath() + "-->" + desDirector + "/" + file[i].getName());

                    copyFileWithDirector(srcDirector + "/" + file[i].getName(), desDirector + "/" + file[i].getName());

                }

            }

        }

 

        /**

         * 删除文件夹

         * @param folderPath folderPath 文件夹完整绝对路径

         */

        public static void delFolder(String folderPath) throws Exception {

 

            //删除完里面所有内容

            delAllFile(folderPath);

            String filePath = folderPath;

            filePath = filePath.toString();

            File myFilePath = new File(filePath);

            //删除空文件夹

            myFilePath.delete();

        }

 

        /**

         * 删除指定文件夹下所有文件

         * @param path 文件夹完整绝对路径

         */

        public static boolean delAllFile(String path) throws Exception {

 

            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()) {

                    temp.delete();

                }

                if (temp.isDirectory()) {

                    //先删除文件夹里面的文件

                    delAllFile(path + "/" + tempList[i]);

                    //再删除空文件夹

                    delFolder(path + "/" + tempList[i]);

                    flag = true;

                }

            }

            return flag;

        }

 

    }


 

[java]一个压缩工具类 zip2008年05月28日 星期三 17:48/*
* Zip.java
*
* Created on 2008年4月2日, 下午2:20
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package com.founder.mnp.utl;

/**
*
* @author GuoJiale
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipUtils {
    static final int BUFFER = 2048;
   
    public static boolean zip( String[] filename ,String outname){
       
        boolean test = true;
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(outname);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];
            // File f= new File("d:\\111\\");
            //   File files[] = f.listFiles();
           
            for (int i = 0; i < filename.length; i++) {
                File file = new File(filename[i]);
                FileInputStream fi = new FileInputStream(file);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(file.getName());
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            test = false;
            e.printStackTrace();
        }
        return test;
    }
  
    public static void main(String argv[]) {
        // File f= new File("d:\\111\\");
        String[] filenames = new String[]{"E:/mnpdata/ad/temp/1209014565259/郁香.jpg"};
        zip(filenames,"c:/myfui.zip");
    }
}
 

 

 

 

0 0
原创粉丝点击