5

我有以下代码:

        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();
        }

但是字符会显示在?这与使用 Unicode 字符的 Java 有关吗?我该如何纠正?

4

6 回答 6

7

您必须知道文件的编码是什么,然后使用该编码将 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();
        }
    }
}
于 2008-09-18T15:39:24.363 回答
3

buf.getChar() 预计每个字符 2 个字节,但您只存储 1 个字节。使用:

 System.out.print((char) buf.get());
于 2008-09-18T15:27:37.340 回答
2

将您的打印声明更改为:

System.out.print((char)buf.get());

似乎有帮助。

于 2008-09-18T15:27:33.050 回答
2

根据 somefile.txt 的编码,一个字符实际上可能不是由两个字节组成。此页面提供了有关如何使用正确编码读取流的更多信息。

令人遗憾的是,文件系统不会告诉你文件的编码,因为它不知道。就它而言,它只是一堆字节。您必须找到某种方法将编码传达给程序,以某种方式检测它,或者(如果可能)始终确保编码相同(例如 UTF-8)。

于 2008-09-18T15:34:20.367 回答
1

您以这种方式读取文件是否有特殊原因?

如果您正在阅读 ASCII 文件,那么您真的应该使用阅读器。

我会这样做:

File inputFile = new File("somefile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));

然后使用其中一个readLine或类似来实际读取数据!

于 2008-09-18T15:21:37.980 回答
0

是的,它是 Unicode。

如果你的文件中有 14 个字符,你只会得到 7 个“?”。

解决方案待定。仍然在想。

于 2008-09-18T15:20:40.417 回答