Java判断文件编码是否为UTF-8

UTF-8文件判断

工程构建及代码

待读取文件
在这里插入图片描述

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.cn.orchid</groupId>
	<artifactId>UTF8Check</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>NoXML</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<logback.version>1.2.5</logback.version>
		<slf4j.version>1.7.32</slf4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.11.0</version>
		</dependency>
	</dependencies>
</project>

App.java

package com.cn.orchid.NoXML;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.cn.orchid.NoXML.config.AppConfig;
import com.cn.orchid.NoXML.controller.NOXmlController;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main(String[] args) {
        File f1 = new File("E:\\1.txt");
        System.out.println(isUTF8(f1));
        File f2 = new File("E:\\1_sjis.txt");
        System.out.println(isUTF8(f2));
        File f3 = new File("E:\\1_bom.txt");
        System.out.println(isUTF8(f3));

    }

    /**
     * 
     * @param file
     * @return
     */
    public static boolean isUTF8(File file) {

        try {

            byte[] buf = FileUtils.readFileToByteArray(file);
            System.out.println(ByteArrayUtil.toHexString(buf));
            String filecCntent = FileUtils.readFileToString(file, "UTF-8");
            System.out.println(ByteArrayUtil.toHexString(filecCntent.getBytes("UTF-8")));

            System.out.println("====================================================================");

            if (ByteArrayUtil.toHexString(buf).equals(ByteArrayUtil.toHexString(filecCntent.getBytes("UTF-8")))) {

                return true;

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值