`
fanjf
  • 浏览: 295863 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

Java操作文件工具类

    博客分类:
  • Java
 
阅读更多

    JAVA API关于操作文件基础类太少,而且缺乏很多使用的方法,在项目开发中往往需要复杂的操作文件。

 

    下面是一个是简单操作文件的工具类。

 

package test.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * 操作文件工具类
 * @author fanjf
 * Version 1.0
 */
public class OperaterFile {
    public static void main(String[] args) throws IOException {
       
        OperaterFile.appendFile("C:/Documents and Settings/Administrator/桌面/1.txt","\n11111", true);
       
        System.out.println("======执行完毕=======");
    }

    /**
     * 判断文件夹是否为空 fanjf
     *
     * @param filePath:文件路径
     */
    public static boolean folderIsNull(String filePath) {
        File file = new File(filePath);

        if (!file.exists() || file.isFile())
            return false;

        String[] fileNameStr = file.list();
        return fileNameStr.length == 0;
    }

    /**
     * 输出目录中的所有文件及目录名字(包含路径)
     *
     * @param filePath:文件路径
     */
    public static Object[] outputFileAndFolder_Path(String filePath) {
        File file = new File(filePath);

        if (!file.exists() || file.isFile())
            return null;

        File[] tempFile = file.listFiles();
        String[] a = new String[tempFile.length];
        String[] b = new String[tempFile.length];
        int aLen = 0;
        int bLen = 0;
        for (int i = 0; i < tempFile.length; i++) {
            if (tempFile[i].isFile() && (!tempFile[i].isHidden())) {
                a[aLen] = tempFile[i].getPath();
                aLen++;
            }
            if (tempFile[i].isDirectory()) {
                b[bLen] = tempFile[i].getPath();
                bLen++;
            }
        }
        String[] fileArray = new String[aLen];
        String[] folderArray = new String[bLen];
        for (int i = 0; i < aLen; i++) {
            fileArray[i] = a[i];
        }
        for (int i = 0; i < bLen; i++) {
            folderArray[i] = b[i];
        }
        return new Object[] {fileArray, folderArray };
    }

    /**
     * 上传文件
     *
     * @param inStream
     * @param newPathName
     */
    public static void uploadFile(InputStream inStream, String newPathName) {
        try {
            int byteread = 0;// 字节数 文件大小
            if (inStream != null)// 文件存在时
            {
                FileOutputStream fs = new FileOutputStream(newPathName);// 写入新文件
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("上传文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 下载文件
     *
     * @param outStream
     * @param filePathName
     */
    public static void downFile(OutputStream outStream, String filePathName) {
        try {
            File file = new File(filePathName);
            InputStream inPut = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = inPut.read(buf)) > 0)
                outStream.write(buf, 0, len);
            inPut.close();
            outStream.close();
        } catch (IOException e) {
            System.out.println("下载文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 移动文件到指定目录
     *
     * @param oldPath
     *            String 如:c:/fqf.txt
     * @param newPath
     *            String 如:d:/fqf.txt
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    /**
     * 移动目录到指定目录
     *
     * @param oldPath
     *            String 如:c:/fqf.txt
     * @param newPath
     *            String 如:d:/fqf.txt
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    /**
     * 复制单个文件
     *
     * @param oldPathName
     *            :原文件路径 如:c:/fqf.txt
     * @param newPathName
     *            :复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public static boolean copyFile(String oldPathName, String newPathName) {
        try {
            int byteread = 0;// 字节数 文件大小
            File oldfile = new File(oldPathName);
            if (oldfile.exists())// 原文件存在时
            {
                InputStream inStream = new FileInputStream(oldPathName); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPathName); // 写入新文件
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    // write(byte[] b, int off, int len)将指定字节数组中从偏移量 off 开始的 len
                    // 个字节写入此文件输出流。
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                return true;
            } else
                // 原文件不存在时
                return false;
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath
     *            String 原文件路径 如:c:/fqf
     * @param newPath
     *            String 复制后路径 如:f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/"
                            + (temp.getName()).toString());
                    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 (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }
    }
   
    /** 判断目录是否含有某扩展名的文件isExistDAT
     * @param filePathName
     * @return
     */
    public static boolean isExistDAT(String filePathName,String DAT){
        File file = new File(filePathName);
        if(!file.exists())
            return false;
//        是文件
        if(file.isFile())
        {
            if(filePathName.endsWith(DAT))
                return true;
            else
                return false;
        }
//        是目录
        if(file.isDirectory())
        {
//            取得目录下的文件
            String[] fileArray = OperaterFile.outputFileName(filePathName);
            for (int i = 0; i < fileArray.length; i++)
            {
                if (fileArray[i].endsWith(DAT))
                    return true;
            }
            return false;
        }
        return false;
    }
    /**
     * 输出目录中的所有文件名
     * @param filePath:目录路径
     */
    public static String[] outputFileName(String filePath) {
        File file = new File(filePath);

        if (!file.exists() || file.isFile())
            return new String[0];

        File[] tempFile = file.listFiles();
        String[] a = new String[tempFile.length];
        int aLen = 0;
        for (int i = 0; i < tempFile.length; i++) {
            if (tempFile[i].isFile() && (!tempFile[i].isHidden())) {
                a[aLen] = tempFile[i].getName();
                aLen++;
            }
        }
        String[] fileArray = new String[aLen];
        for (int i = 0; i < aLen; i++) {
            fileArray[i] = a[i];
        }
        return fileArray;
    }

    /**
     * 创建目录:若目录已存在,则先删除再创建。
     *
     * @param folderName
     *            目录名
     * @param filePath
     *            目录路径
     * @return 删除成功返回true
     */
    public static boolean createFolder(String filePath, String folderName) {
        try {
            File file = new File(filePath + folderName);
            if (file.exists()) {
                boolean del = delFolder(filePath + folderName);// 删除目录,以及其中的所有文件。
                file.mkdirs();
                return true;
            } else {
                file.mkdirs();
                return true;
            }
        } catch (Exception ex) {
            System.out.println("CreateAndDeleteFolder is error:" + ex);
            return false;
        }

    }

    /**
     * 创建文件:若文件已存在,先删除再创建。
     *
     * @param filePath
     *            文件路径
     * @param fileName
     *            文件名
     * @return 创建成功返回true
     * @throws IOException
     */
    public static boolean createFile(String filePath, String fileName, String fileContent)
            throws IOException {
        boolean result = false;
        File file = new File(filePath, fileName);
        if (file.exists()) {
            file.delete();
            file.createNewFile();
            result = true;
        } else {
            file.createNewFile();
            result = true;
        }
        FileWriter resultFile = new FileWriter(file);
        PrintWriter myFile = new PrintWriter(resultFile);
        myFile.println(fileContent);
        resultFile.close();
        return result;
    }

    /**
     * 新建文件,并写入内容:若文件目录不存在,则先创建文件目录。
     *
     * @param filePathAndName
     *            文件路径及名称 如c:/fqf.txt
     * @param fileContent
     *            文件内容
     * @return boolean
     */
    public static void newFile(String filePath, String fileName, String fileContent) {
        try {
            newFolder(filePath);// 创建目录
            File myFilePath = new File(filePath + fileName);
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            FileWriter resultFile = new FileWriter(myFilePath);
            PrintWriter myFile = new PrintWriter(resultFile);
            myFile.println(fileContent);
            resultFile.close();
        } catch (Exception e) {
            System.out.println("新建文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 新建目录:若目录已存在,则不创建,否则创建。
     *
     * @param folderPath
     *            String 如 c:/fqf
     * @return boolean
     */
    public static void newFolder(String folderPath) {
        try {
            File myFilePath = new File(folderPath);
            if (!myFilePath.exists()) {
                myFilePath.mkdirs();
            }
        } catch (Exception e) {
            System.out.println("新建目录操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 检查文件中是否为一个空
     *
     * @param filePath
     * @param fileName
     * @return 为空返回true
     * @throws IOException
     */
    public static boolean fileIsNull(String filePath, String fileName) throws IOException {
        boolean result = false;
        FileReader fr = new FileReader(filePath + fileName);
        if (fr.read() == -1)// 文件中没有数据
        {
            result = true;
        }
        fr.close();
        return result;
    }

    /**
     * 逐行读取文件中的所有内容
     *
     * @param filePath
     * @param fileName
     * @throws IOException
     */
    public static String readLineFile(String filePath, String fileName) throws IOException {
        StringBuffer fileContent = new StringBuffer();
        FileReader fr = new FileReader(filePath + fileName);
        int count = fr.read();
        while (count != -1) {
            // System.out.print((char) count);
            fileContent.append((char) count);
            count = fr.read();
            if (count == 13) {
                fr.skip(1);
            }
        }
        fr.close();
        return fileContent.toString();
    }

    /**
     * 一行一行的读取文件中的数据
     *
     * @param filePathName
     *            文件路径+文件名
     * @throws IOException
     */
    public static String readLineFile(String filePathName) throws IOException {
        StringBuffer fileContent = new StringBuffer();
        try {
            FileReader fr = new FileReader(filePathName);
            BufferedReader br = new BufferedReader(fr);
            String line = br.readLine();
            while (line != null) {
                fileContent.append(line + "\n");
                line = br.readLine();
            }
            br.close();
            fr.close();
        } catch (Exception d) {
            System.out.println(d.getMessage());
        }
        return fileContent.toString(); // 返回从文本文件中读取内容
    }

    /**
     * 统一读取文件
     *
     * @param filePathName
     *            文件路径+文件名
     * @return
     */
    public static String readfile(String filePathName) throws IOException {
        String read;
        String readStr = "";
        try {
            File file = new File(filePathName); // 得到文本文件的路径
            FileReader fileread = new FileReader(file);
            BufferedReader bufread = new BufferedReader(fileread);
            while ((read = bufread.readLine()) != null) {
                readStr = readStr + read;
            }
        } catch (Exception d) {
            System.out.println(d.getMessage());
        }
        return readStr; // 返回从文本文件中读取内容
    }

    /**
     * 文件的写入
     *
     * @param filePathName:文件路径+文件名
     * @param args:文件内容
     * @throws IOException
     */
    public static void writeFile(String filePathName, String args) throws IOException {
        FileWriter fw = new FileWriter(filePathName);
        fw.write(args);
        fw.close();
    }

    /**
     * 文件的写入
     *
     * @param filePath:文件路径
     * @param fileName:文件名
     * @param args:文件内容
     * @throws IOException
     */
    public static void writeFile(String filePath, String fileName, String args) throws IOException {
        FileWriter fw = new FileWriter(filePath + fileName);
        fw.write(args);
        fw.close();
    }

    /**
     * 文件的逐行写入
     *
     * @param filePathName:文件路径+文件名
     * @param args[]
     *            文件内容的每行数据
     * @throws IOException
     */
    public static void writeLineFile(String filePathName, String[] args) throws IOException {
        FileWriter fw = new FileWriter(filePathName);
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < args.length; i++) {
            out.write(args[i]);
            out.println();
            out.flush();
        }
        fw.close();
        out.close();
    }

    /**
     * 文件的逐行写入
     *
     * @param filePath:文件路径
     * @param fileName:文件名
     * @param args[]
     *            文件内容的每行数据
     * @throws IOException
     */
    public static void writeLineFile(String filePath, String fileName, String[] args)
            throws IOException {
        FileWriter fw = new FileWriter(filePath + fileName);
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < args.length; i++) {
            out.write(args[i]);
            out.println();
            out.flush();
        }
        fw.close();
        out.close();
    }

    /**
     * 向文本文件中重新写入或追加内容
     *
     * @param filePathName
     *            得到文本文件的路径+文件名
     * @param fileContent
     *            需要写入的内容
     * @param append
     *            通过这个对象来判断是否向文本文件中追加内容
     */
    public static void appendFile(String filePathName, String fileContent, boolean append) {
        try {
            File file = new File(filePathName);
            if (file.exists() == false) // 如果文本文件不存在则创建它
            {
                file.createNewFile();
                file = new File(filePathName); // 重新实例化
            }
            FileWriter fileWriter = new FileWriter(file, append);
            BufferedWriter bufwriter = new BufferedWriter(fileWriter);
            fileWriter.write(fileContent);
            fileWriter.flush();
        } catch (Exception d) {
            System.out.println(d.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param filePathAndName
     *            文件路径及名称 如c:/fqf.txt
     * @return boolean
     */
    public static boolean delFile(String filePathAndName) {
        try {
            File myDelFile = new File(filePathAndName);
            return myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除文件夹
     *
     * @param filePathAndName
     *            文件夹路径及名称 如c:/fqf
     * @return boolean
     */
    public static boolean delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除文件夹中的所有内容
            File myFilePath = new File(folderPath);
            return myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            System.out.println("删除文件夹操作出错");
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除文件夹里面的所有文件 fanjf
     *
     * @param path String 文件夹路径 如 c:/fqf
     */
    public static boolean delAllFile(String path) {
        File file = new File(path);
        if (!file.exists())// 文件夹不存在
        {
            return false;
        }
        if (!file.isDirectory())// 不是文件夹
        {
            return false;
        } else// 是文件夹
        {
            File[] tempFile = file.listFiles();
            for (int i = 0; i < tempFile.length; i++) {
                if (tempFile[i].isDirectory()) {
                    delFolder(tempFile[i].toString());
                }
                if (tempFile[i].isFile()) {
                    tempFile[i].delete();
                }
            }
            return true;
        }
    }

    /**
     * 删除文件夹里面的所有文件
     *
     * @param path
     *            String 文件夹路径 如 c:/fqf
     */
    public static void delAllFile2(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        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]);// 再删除空文件夹
            }
        }
        // file.delete();// 删除空文件夹
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics