BOM이없는 파일의 인코딩을 식별하려고 할 때 특히 파일이 비 ASCII 문자로 시작될 때 문제가 발생합니다.BOM을 사용하지 않고 비 ASCII 문자로 시작하는 파일에 대해 다른 인코딩을 어떻게 식별 할 수 있습니까?
내가 파일을 인코딩을 식별하는 방법에 대한 두 가지 주제를 다음과 발견, 현재
, 나는 파일을 다른 인코딩을 식별하는 클래스를 생성 (예 : UTF-8, UTF-16, UTF-32, UTF-16 없음 BOM 등)
위의 코드는 모든 경우 BOM없이 파일을 ASCII 문자가 아닌 문자로 시작하는 경우를 제외하고는 제대로 작동 할 수
public class UnicodeReader extends Reader {
private static final int BOM_SIZE = 4;
private final InputStreamReader reader;
/**
* Construct UnicodeReader
* @param in Input stream.
* @param defaultEncoding Default encoding to be used if BOM is not found,
* or <code>null</code> to use system default encoding.
* @throws IOException If an I/O error occurs.
*/
public UnicodeReader(InputStream in, String defaultEncoding) throws IOException {
byte bom[] = new byte[BOM_SIZE];
String encoding;
int unread;
PushbackInputStream pushbackStream = new PushbackInputStream(in, BOM_SIZE);
int n = pushbackStream.read(bom, 0, bom.length);
// Read ahead four bytes and check for BOM marks.
if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
encoding = "UTF-8";
unread = n - 3;
} else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
encoding = "UTF-16BE";
unread = n - 2;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
encoding = "UTF-16LE";
unread = n - 2;
} else if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
encoding = "UTF-32BE";
unread = n - 4;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
encoding = "UTF-32LE";
unread = n - 4;
} else {
// No BOM detected but still could be UTF-16
int found = 0;
for (int i = 0; i < 4; i++) {
if (bom[i] == (byte) 0x00)
found++;
}
if(found >= 2) {
if(bom[0] == (byte) 0x00){
encoding = "UTF-16BE";
}
else {
encoding = "UTF-16LE";
}
unread = n;
}
else {
encoding = defaultEncoding;
unread = n;
}
}
// Unread bytes if necessary and skip BOM marks.
if (unread > 0) {
pushbackStream.unread(bom, (n - unread), unread);
} else if (unread < -1) {
pushbackStream.unread(bom, 0, 0);
}
// Use given encoding.
if (encoding == null) {
reader = new InputStreamReader(pushbackStream);
} else {
reader = new InputStreamReader(pushbackStream, encoding);
}
}
public String getEncoding() {
return reader.getEncoding();
}
public int read(char[] cbuf, int off, int len) throws IOException {
return reader.read(cbuf, off, len);
}
public void close() throws IOException {
reader.close();
}
}. 이 상황에서 BOM이없는 파일이 여전히 UTF-16인지 확인하는 논리는 올바르게 작동하지 않으므로 인코딩은 기본적으로 UTF-8로 설정됩니다.
BOM이없는 파일의 인코딩을 검사하고 비 ASCII 문자로 시작하는 방법이있는 경우, 특히 UTF-16 NO BOM 파일의 경우?
감사합니다. 어떤 아이디어라도 감사 할 것입니다.
경험적 방법 ... 많은 경우에 프로그램의 * 많은 * (Un * x * file * 명령이 놀라운 예입니다)에 의해 수행됩니다. 나는 "수동으로"(잘 작동하는 내 자신의 휠을 발명)했지만 요즘에는 단순히 "Stephen C"의 대답을 받아 들일 것입니다. 기존 코드를 이미 다시 사용하십시오. – SyntaxT3rr0r
@ SyntaxT3rr0r : 그래,이 문제를 해결하는 좋은 방법입니다. 타사 라이브러리를 제품에 도입하는 데 한계가 있기 때문에 필자가 제공 한 코드를 개선하여 자체 휠을 사용하는 것이 좋습니다. – eagles