ファイルのエンコード形式をJavaで判定する

Javaではjava.nio.charset.Charsetクラスを使用してファイルのエンコーディングを調べることができます。Charset.forName(String charsetName)メソッドを使用してファイルのエンコーディングに基づいて適切なCharsetオブジェクトを取得できます。その後、CharsetDecoderクラスのdecode(ByteBuffer buffer)メソッドを使用してファイル内容を文字にデコードします。

これはサンプルコードです。

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileEncodingDetection {
    public static void main(String[] args) {
        String filePath = "path/to/file.txt";
        Path path = Paths.get(filePath);

        try {
            CharsetDetector detector = new CharsetDetector();
            Charset charset = detector.detectCharset(path);
            System.out.println("文件编码格式: " + charset.displayName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class CharsetDetector {
        public Charset detectCharset(Path path) throws Exception {
            byte[] bytes = Files.readAllBytes(path);
            CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
            decoder.reset();
            decoder.decode(ByteBuffer.wrap(bytes));
            return decoder.charset();
        }
    }
}

CharsetDetectorクラスを作成し、そのクラスのdetectCharset(Path path)メソッドでファイル内容を読み取り、文字エンコーディングを判別しています。detectCharset()メソッドでは、まずファイルのすべてのバイト内容を読み込み、次にStandardCharsets.UTF_8のCharsetDecoderを使用してバイト内容をデコードし、最後にデコード後のCharsetオブジェクトを返します。

mainメソッドでは、まずファイルのパスを設定し、Pathオブジェクトを作成します。次に、CharsetDetectorクラスのdetectCharsetメソッドを使用してファイルのエンコード形式を判定し、最後にその結果を出力します。

广告
広告は10秒後に閉じます。
bannerAds