Java读取不同编码格式的文件

wylc123 1年前 ⋅ 2198 阅读
private static String getCharset(String fileName) throws IOException {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
				fileName));
		int p = (bin.read() << 8) + bin.read();
		String code = null;
 
		switch (p) {
		case 0xefbb:
			code = "UTF-8";
			break;
		case 0xfffe:
			code = "Unicode";
			break;
		case 0xfeff:
			code = "UTF-16BE";
			break;
		default:
			code = "GBK";
		}
		return code;
	}
 
	public static StringBuffer getTextFromText(String filePath) {
		StringBuffer sb = null;
		try {
			InputStreamReader isr = new InputStreamReader(new FileInputStream(
					filePath), getCharset(filePath));
			BufferedReader br = new BufferedReader(isr);
 
			sb = new StringBuffer();
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb;
	}
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: