FileChannel 및 ByteArrays를 사용하여 ASCII 파일 읽기
-
01-07-2019 - |
문제
다음 코드가 있습니다.
String inputFile = "somefile.txt";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
for ( int i = 0; i < rd/2; i++ ) {
/* print each character */
System.out.print(buf.getChar());
}
buf.clear();
}
그러나 문자는 ?에 표시됩니다.이것이 유니코드 문자를 사용하는 Java와 관련이 있습니까?이 문제를 어떻게 수정합니까?
해결책
파일의 인코딩이 무엇인지 알아야 하며 해당 인코딩을 사용하여 ByteBuffer를 CharBuffer로 디코딩해야 합니다.파일이 ASCII라고 가정합니다.
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Buffer
{
public static void main(String args[]) throws Exception
{
String inputFile = "somefile";
FileInputStream in = new FileInputStream(inputFile);
FileChannel ch = in.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256
Charset cs = Charset.forName("ASCII"); // Or whatever encoding you want
/* read the file into a buffer, 256 bytes at a time */
int rd;
while ( (rd = ch.read( buf )) != -1 ) {
buf.rewind();
CharBuffer chbuf = cs.decode(buf);
for ( int i = 0; i < chbuf.length(); i++ ) {
/* print each character */
System.out.print(chbuf.get());
}
buf.clear();
}
}
}
다른 팁
buf.getChar()는 문자당 2바이트를 예상하지만 1바이트만 저장합니다.사용:
System.out.print((char) buf.get());
인쇄 명세서를 다음으로 변경:
System.out.print((char)buf.get());
도움이 될 것 같습니다.
somefile.txt의 인코딩에 따라 문자가 실제로 2바이트로 구성되지 않을 수도 있습니다. 이 페이지 적절한 인코딩으로 스트림을 읽는 방법에 대한 자세한 정보를 제공합니다.
안타까운 점은 파일 시스템이 파일의 인코딩을 알지 못하기 때문에 파일의 인코딩을 알려주지 않는다는 것입니다.그것에 관한 한 그것은 단지 바이트 묶음일 뿐입니다.인코딩을 프로그램에 전달하는 방법을 찾거나, 어떻게든 이를 감지하거나, 가능하다면 인코딩이 항상 동일한지(예: UTF-8) 확인해야 합니다.
당신이 하는 방식으로 파일을 읽는 특별한 이유가 있습니까?
ASCII 파일을 읽는다면 실제로는 Reader를 사용해야 합니다.
나는 다음과 같이 할 것입니다 :
File inputFile = new File("somefile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
그런 다음 다음 중 하나를 사용하십시오. readLine
또는 실제로 데이터를 읽는 것과 유사합니다!
예, 유니코드입니다.
파일에 14개의 문자가 있으면 '?'는 7개만 표시됩니다.
해결책이 보류 중입니다.아직도 생각 중입니다.
제휴하지 않습니다 StackOverflow