`
fanjf
  • 浏览: 335447 次
  • 性别: 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();// 删除空文件夹
    }
}

分享到:
评论

相关推荐

    java 操作文件工具类 java 操作文件工具类

    java 操作文件工具类java 操作文件工具类 java 操作文件工具类java 操作文件工具类java 操作文件工具类 java 操作文件工具类java 操作文件工具类java 操作文件工具类 java 操作文件工具类java 操作文件工具类java ...

    java操作文件工具类

    文件工具类java操作文件工具类java操作文件工具类java操作文件工具类java操作文件工具类

    java文件操作工具类

    java文件操作工具类是java中针对文件操作的一个工具类,可以方便的读取,下载,上传文件等操作,希望可以帮到大家。

    java实现对文件的各种操作的工具类.md

    # java实现对文件的各种操作的工具类 ## 可以实现的操作有: 1. 删除单个文件 2. 删除文件夹及文件夹下的文件 3. 使用文件流对单个文件进行复制 4. 复制整个文件夹内容(包含子文件夹中的所有内容) 5. ...

    完整的java文件读写工具类

    本篇将详细讲解标题为"完整的java文件读写工具类"所涉及的核心知识点,以及如何实现描述中提到的文件与目录管理功能。 1. **Java IO基础**: Java IO是Java标准库中的核心部分,提供了处理输入/输出流的类。在`...

    java操作word文件工具类级dell文件

    Java操作Word文件主要涉及到的是对Microsoft Office文档的处理,这在很多企业级应用中非常常见,比如自动化报告生成、数据导入导出等。在Java中,由于Java本身并不直接支持与Windows API交互,因此需要借助第三方库...

    Java文件处理工具类--FileUtil

    import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /**...

    java properties文件操作工具类,可追加修改

    此工具类只用于Java后端在操作Properties文件的时候写的工具类,方便properties文件的存取操作

    java 中 zip压缩文件解压工具类

    本文将深入探讨如何使用Java来处理ZIP文件,特别是针对标题所提及的“java 中 zip压缩文件解压工具类”。我们将讨论核心的Java API,如`java.util.zip`包中的类,并通过一个名为`CompressFileUtils`的工具类来展示...

    java csv文件读取工具类

    一个非常好用的csv文件操作工具

    自己写的java中文件的操作工具类,包括对目录的管理

    这个“自己写的java中文件的操作工具类”显然提供了一种自定义的方式来管理和操作文件及目录。下面将详细介绍相关知识点: 1. **文件操作**:在Java中,`java.io`包提供了丰富的类来执行文件操作,如`File`类用于...

    java操作redis工具类

    java操作redis工具类 可以支持单个redis对象或者是连接池 支持分片

    java操作Access数据库文件工具类

    标题中的“Java操作Access数据库文件工具类”指的是使用Java编程语言来与Microsoft Access数据库进行交互的工具类。在Java中,我们通常通过JDBC(Java Database Connectivity)API来实现这样的功能,它允许Java程序...

    java 文件操作工具类

    java 文件操作工具类

    java操作sftp的工具类(JSch)

    Java操作SFTP(Secure File Transfer Protocol)主要依赖于第三方库,如JSch。JSch是一个纯Java实现的SSH2库,允许开发人员连接到支持SFTP的服务器,进行文件的上传、下载以及执行其他相关操作。本文将详细介绍如何...

    java文件上传下载工具类

    总结起来,"java文件上传下载工具类"是Java Web开发中不可或缺的部分,它封装了与文件操作相关的复杂逻辑,使开发者能够更专注于业务逻辑。通过创建这样的工具类,可以提高代码的可复用性和可维护性,同时降低出错的...

    java文件操作的工具类

    此文档为java中操作File对象的一个通用工具类,包含了byte数组和File类的相互转换

    java读写文件工具类

    大家可以不用在为操作文件发愁了! 小弟觉得这个工具类还不是很完善,高手在帮忙完善一下,别忘了共享出来哦!

    java File文件处理工具类

    Java中的`File`类是Java I/O流体系中不可或缺的一部分,它是用来操作文件和目录的基础类。`File`对象代表了文件和目录路径名的抽象表示。在这个详细的讲解中,我们将深入探讨`File`类的各种功能,包括创建、读取、...

    java操作excel工具类

    Java操作Excel工具类是开发过程中常见的一种需求,尤其是在数据导入导出、数据分析或者报表生成的场景下。在Java中,我们可以使用多种库来处理Excel文件,例如Apache POI、JExcelAPI、OpenCSV等。本篇文章将重点介绍...

Global site tag (gtag.js) - Google Analytics