栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 文件操作相关工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 文件操作相关工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


public class YcsFileUtils {
    
    public static final int BLOCK = 4 * 1024;

    
    public static void readBytes(String filePath, OutputStream os) {
        try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
            byte[] b = new byte[BLOCK];
            int length;
            while ((length = fileInputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取文件的byte数组到输出流失败!filePath = " + filePath + "n" + e);
        }
    }

    
    public static void writeBytes(byte[] data, String filePath) {
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            outputStream.write(data);
        } catch (IOException e) {
            throw new RuntimeException("写入byte数组数据到文件中!filePath = " + filePath + "n" + e);
        }
    }

    
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    
    public static String getFileType(String fileName) {
        int separatorIndex = fileName.lastIndexOf(File.separator);
        if (separatorIndex < 0) {
            return "";
        }
        return fileName.substring(separatorIndex + 1).toLowerCase();
    }

    
    public static String getFileExtendName(byte[] photoByte) {
        if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
            return "gif";
        }

        if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
            return "jpg";
        }

        if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
            return "bmp";
        }

        if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
            return "png";
        }

        throw new RuntimeException("获取文件真实类型失败!");
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/679071.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号