阅读ASCII文件与FileChannel和ByteArrays
-
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();
}
但人物得到显示在?'s。这不会有事情做Java使用Unicode的人物?我该如何纠正这个吗?
解决方案
你必须知道哪些文件的编码,然后解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。形式()是期待2个字节每字但你只是储存1.使用:
System.out.print((char) buf.get());
改变你的打印的发言:
System.out.print((char)buf.get());
似乎有帮助。
根据编码的somefile.txt一字实际上可能不是由两个字节。 这页 提供了更多的信息,关于如何解读流与适当的编码。
这令人失望的是,文件系统并没有告诉你编的文件,因为它不知道。就因为它的关切,它只是一堆字节。你必须找到某种方式沟通的编码的程序,检测到它在某种程度上,或者(如果可能的话)始终确保编码是一样的(例如UTF-8).
是否有一个特别的原因,为什么你正在读的文件中,你做的?
如果你正在读在ASCII文件,你真的应该用一个读者。
我会做这样的东西:
File inputFile = new File("somefile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
然后使用 readLine
或者类似实际上读取的数据。
是的,这是Unicode。
如果你有14字在你的文件中,你只能得到7'?'.
解决悬而未决。仍然思维。
不隶属于 StackOverflow