Java判断文件的系统格式编码格式

使用Java判断一个文件的系统格式(亲测可用),比如我们常见的Windows格式的文件,Unixg格式的文件,Mac格式的文件;常常有这样的场景:我们在Windows系统编写的脚步上传到Linux系统执行,执行过程中偶尔会出现各种各样奇怪的问题,然后还找不到原因!好了,大概率是脚本系统格式问题。

一、首先来看一下不使用代码程序的情况下怎么查看文件的格式

1.如果有notepad++,直接打开查看右下角,既可以查看当前的文件系统格式,也可以直接点击修改

 2.用vim命令,命令行模式下:set ff 就可以查看当前的文件系统格式,:set ff=unix 就可以修改当前的文件格式

 二、使用Java代码判断文件的系统格式

public static void main(String[] args) {
        String filePath = "F:\\temp\\1.sh";
        System.out.println(getFileSystemFormat(filePath));
    }

    public static String getFileSystemFormat(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不在,路径:" + filePath);
            return "undefined";
        }
        try (FileInputStream in = new FileInputStream(filePath)) {
            StringBuffer systemFormat = new StringBuffer();
            int count;
            int i = 0;
            while ((count = in.read()) != -1) {
                //CR: ASCII: 13
                if (count == 13) {
                    systemFormat.append(count);
                    i++;
                }
                //LF: ASCII: 10
                if (count == 10) {
                    systemFormat.append(count);
                    i++;
                }
                if (i == 2) break;
            }
            if (systemFormat.toString().contains("1313")) {
                return "Mac";
            }
            if (systemFormat.toString().contains("1310")) {
                return "Windows";
            }
            if (systemFormat.toString().contains("1010")) {
                return "Unix";
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception e");
        }
        return "undefined";
    }

亲测可用!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值