Java 获取文件内容编码格式:方法解析
Java 中可以通过以下两种方式获取文件内容的编码格式:
- 使用 Java NIO 的 Charset 类来判断文件编码格式:
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileEncoding {
public static void main(String[] args) throws Exception {
Path path = Path.of("/path/to/file.txt");
Charset charset = Files.readAllLines(path, StandardCharsets.UTF_8).stream()
.collect(Collectors.joining()).getBytes().length > 0
? Charset.defaultCharset() : StandardCharsets.UTF_8;
System.out.println('File encoding: ' + charset);
}
}
- 使用第三方库 ICU4J 来判断文件编码格式:
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class FileEncoding {
public static void main(String[] args) throws Exception {
String filePath = "/path/to/file.txt";
try (InputStream is = new BufferedInputStream(new FileInputStream(filePath))) {
CharsetDetector detector = new CharsetDetector();
detector.setText(is);
CharsetMatch match = detector.detect();
System.out.println('File encoding: ' + match.getName());
}
}
}
以上两种方式都可以用来获取文件内容的编码格式,具体使用哪种方式取决于具体的需求和环境。
原文地址: https://www.cveoy.top/t/topic/nY8L 著作权归作者所有。请勿转载和采集!