Kenmegne
7 days ago 23a46b4be35277e06ec89f48730eeb694e686be8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.megatim.fdxcommons.tools;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import org.apache.tika.parser.txt.CharsetDetector;
import org.apache.tika.parser.txt.CharsetMatch;
 
/**
 *
 * @author ASUS
 */
public class FileUtilities {
    public static Charset getCharset(File file) throws FileNotFoundException, IOException {
        
        try ( InputStream stream = new FileInputStream(file);  InputStream input = new BufferedInputStream(stream);) {
            CharsetDetector charsetDetector = new CharsetDetector();
 
            charsetDetector.setText(input);
 
            CharsetMatch charsetMatch = charsetDetector.detect();
            String charsetName = charsetMatch != null ? charsetMatch.getName() : "UTF-8";
 
            return Charset.forName(charsetName);
 
        } catch(UnsupportedCharsetException ex) {
             return Charset.forName("UTF-8");
        }
    }
}