---
title: "java检查文本文件编码格式"
author: "rabby"
date: "2011-05-24T22:02:39Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-05-24T22:02:39Z"
id: 1057189
url: "https://rabby.iteye.com/blog/1057189"
---

```
public static String getEncoding(File file) {
		String encoding = "GBK";
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
			byte[] b = new byte[3];
			fileInputStream.read(b);
			if (b[0] == -17 && b[1] == -69 && b[2] == -65) {
				encoding = "UTF-8";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != fileInputStream) {
				try {
					fileInputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return encoding;
	}
```