| | |
| | | public static String detectFromInputStream(InputStream inputStream) { |
| | | UniversalDetector detector = new UniversalDetector(null); |
| | | //开始给一部分数据,让学习一下啊,官方建议是1000个byte左右(当然这1000个byte你得包含中文之类的) |
| | | byte[] buffer = new byte[1024]; |
| | | byte[] buffer = new byte[2048]; |
| | | try { |
| | | int actRead = inputStream.read(buffer); |
| | | |
| | |
| | | return detector.getDetectedCharset(); |
| | | } |
| | | |
| | | /** |
| | | * 从输入流获取文本 |
| | | * @param ins 束流 |
| | | * @return 文本字符 |
| | | * @throws IOException |
| | | */ |
| | | public static String getContentFromStream(InputStream ins) throws IOException { |
| | | byte[] bytes = ins.readAllBytes(); |
| | | ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); |
| | | Charset charset = Charsets.charset(detectFromInputStream(byteStream)); |
| | | byteStream.reset();//重置,使继续可用 |
| | | |
| | | return new String(bytes, charset); |
| | | } |
| | | } |