import com.foriseland.fjf.lang.DateUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @ClassName FileUtil
 * @Description
 * @Author zhangyue
 * @Date 2018/1/9 20:58
 */
public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

/**
     * 根据byte数组,生成文件
     */
    public static void getFile(byte[] bfile, String filePath,String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath+"\\"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

/**
     * byte[] 转InputStream
     */
    public static final InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

/**
     * InputStream 转 byte[]
     * @param inStream
     * @return
     * @throws IOException
     */
    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

/**
     * byte[] 转 InputStreamReader
     */
    public static final InputStreamReader byte2Reader(byte[] buf) {
        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(buf));
        return isr;
    }

/**
     * 删除文件
     *
     * @param pathname
     *          文件名(包括路径)
     */
    public static void deleteFile(String pathname){

File file = new File(pathname);
        if(file.isFile() && file.exists()){
            file.delete();
        }
        else{
            logger.error("File["+ pathname +"] not exists!");
        }

}

/**
     * 删除文件树
     *
     * @param dirpath
     *          文件夹路径
     */
    public static void deleteFileTree(String dirpath) throws IOException {

File dir = new File(dirpath);
        FileUtils.deleteDirectory(dir);
    }

/**
     * 获取文件扩展名
     *
     * @param fileName
     *            文件名
     * @return
     */
    public static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
    }

/**
     * 获取文件分隔符
     *
     * @return
     */
    public static String getFileSeparator() {
        return File.separator;
    }

/**
     * 获取相对路径
     *
     * @param params
     *          按参数先后位置得到相对路径
     * @return
     */
    public static String getRelativePath(String... params){

if(null != params){
            String path = "";
            for(String str : params){
                path = path + getFileSeparator() + str;
            }

return path;
        }

return null;
    }

/**
     * 把一个字符串写到指定文件中
     * @param str  要写入文件中的字符串内容
     * @param path 文件夹路径
     * @param fileName 文件名称
     */
    public static void writeStringToFile(String str,String path,String fileName) throws IOException {
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        File file = new File(path+fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file,true);
        fw.write(str);
        fw.flush();
        fw.close();
    }

/**
     * 在某个文件中追加内容
     * @param fileName
     * @param content
     */
    public static void appendStringToFile(String fileName, String content) {
        try {
            //判断文件是否存在
            File file = new File(fileName);
            judeFileExists(file);
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.write((content + "\r\n").getBytes());
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

// 判断文件是否存在,如果不存在则创建
    public static void judeFileExists(File file) {
        if (file.exists()) {
        } else {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

// 判断文件夹是否存在,如果不存在则创建
    public static void judeDirExists(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }
    }

}

Java文件操作工具类的更多相关文章

  1. JAVA文件操作工具类(读、增、删除、复制)

    使用JAVA的JFinal框架 1.上传文件模型类UploadFile /** * Copyright (c) 2011-2017, James Zhan 詹波 (jfinal@126.com). * ...

  2. Java文件操作工具类(复制、删除、重命名、创建路径)

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...

  3. Code片段 : .properties属性文件操作工具类 & JSON工具类

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 j ...

  4. 文件操作工具类: 文件/目录的创建、删除、移动、复制、zip压缩与解压.

    FileOperationUtils.java package com.xnl.utils; import java.io.BufferedInputStream; import java.io.Bu ...

  5. Android文件操作工具类(转)

    Android文件操作工具类(转)  2014/4/3 18:13:35  孤独的旅行家  博客园 这个工具类包含Android应用开发最基本的几个文件操作方法,也是我第一次发博客与大家分享自己写的东 ...

  6. 小米开源文件管理器MiCodeFileExplorer-源码研究(4)-文件操作工具类FileOperationHelper

    文件操作是非常通用的,注释都写在源代码中了,不多说~需要特别说明的是,任务的异步执行和IOperationProgressListener.拷贝和删除等操作,是比较费时的,采用了异步执行的方式~ An ...

  7. docker 部署vsftpd服务、验证及java ftp操作工具类

    docker部署vsftpd服务 新建ftp文件存储目录/home/ftp cd /home mkdir ftp 创建一个组,用于存放ftp用户 groupadd ftpgroups 创建ftp用户, ...

  8. JAVA文件操作类和文件夹的操作代码示例

    JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...

  9. 【安卓】安卓res文件夹下的资源文件与R.java文件里面类的对应关系

    对于drawable.layout.menu文件夹下的每一个文件都分别会在R.java文件里面生成drawable.layout.menu类的一个常量,类名就是文件夹的名字,常量的名字就是文件名字. ...

随机推荐

  1. C++析构函数(转)

    创建对象时系统会自动调用构造函数进行初始化工作,同样,销毁对象时系统也会自动调用一个函数来进行清理工作(例如回收创建对象时消耗的各种资源),这个函数被称为析构函数. 析构函数(Destructor)也 ...

  2. Ubuntu 下常用的命令 简略记录

    # 动态显示 NVIDIA watch -n 1 nvidia-smi #查看某一目录下文件的总数(不包含子目录) ls -l | wc -l #挂载硬盘或者U盘 mount /dev/sdb1 /m ...

  3. 入门Promise的正确姿势

    Promise是异步编程的一种解决方案,从语法上说,Promise是一个对象,从它可以获取异步操作的消息. Promise的基本用法 Promise构造函数接受一个函数作为参数,该函数的两个参数分别是 ...

  4. step2: 爬取廖雪峰博客

    #https://zhuanlan.zhihu.com/p/26342933 #https://zhuanlan.zhihu.com/p/26833760 scrapy startproject li ...

  5. asp get与post获取的区别

    1.HTTP请求格式: <request line> <headers> <blank line> [<request-body>] 在HTTP请求中, ...

  6. MYSQL连接字符串参数解析(解释)

    被迫转到MySQL数据库,发现读取数据库时,tinyint类型的值都被转化为boolean了,这样大于1的值都丢失,变成true了.查阅资料MySQL中无Boolean类型,都是存储为tinyint了 ...

  7. Expression Blend实例中文教程(1) - 开篇

    随着计算机软件开发分工细节化,微软对已有的产品线进行了调整,在保持原有经典开发工具Visual Studio基础上,又推出了一套新的设计开发工具系列,Expression Studio. Expres ...

  8. python监控linux内存并写入mongodb

    (需要安装psutil 用来获取服务器资源,以及pymongo驱动)#pip install psutil #pip install pymongo #vim memory_monitory.py 文 ...

  9. Java 方法重载和多态

    先来看看什么是方法重载? 方法重载的要求是:方法名相同,参数列表不同(不同的参数类型或者参数顺序或者参数个数).至于方法的其他部分,如方法返回值类型和修饰符,与方法重载没有任何关系.最好加上@Over ...

  10. thinkphp怎么把数据库中的列的值存到下拉框中

    1. 先去数据库中查值,查询整个数据表,结果为二维数组. $project = M("project"); $cell = $project->where(array('st ...