如果文本文件是按照GBK编码的,则解码、编码都应该没有异常。
代码如下:
import java.io.*; public class Main { public static void main(String[] args) throws IOException { String filePath = "D:/temp/temp.txt"; String str = "AAAAA\n我的成功之路\n66666\n一路畅通。"; PrintWriter writer = new PrintWriter(filePath, "UTF-8"); writer.println(str); writer.flush(); writer.close(); if (isGBK(filePath) == true) { System.out.println(filePath + ": GBK格式。"); } else { System.out.println(filePath + ": 不是GBK格式。"); } writer = new PrintWriter(filePath, "GBK"); writer.println(str); writer.flush(); writer.close(); if (isGBK(filePath) == true) { System.out.println(filePath + ": GBK格式。"); } else { System.out.println(filePath + ": 不是GBK格式。"); } } public static boolean isGBK(String path){ String str = null; int counter = 0; int error = 0; try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"))) { while ((str = br.readLine()) != null) { counter ++; if (java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(str) == false) { error ++; } } } catch (Exception ex) { System.out.println(ex.getMessage()); } if (counter < 1 || error < 1) { return true; } else { return false; } } }
运行结果:
D:/temp/temp.txt: 不是GBK格式。
D:/temp/temp.txt: GBK格式。