0

我正在尝试使用文件通道来读取一个大的 xml 文件,这里是我在这里找到的示例代码。当我尝试它时,它打印出无法识别的字符: import java.io.File; 导入java.io.File;导入 java.io.FileInputStream;导入 java.nio.ByteBuffer;导入 java.nio.channels.FileChannel;

public class MainClass {
  public static void main(String[] args) throws Exception {
    File aFile = new File("charData.xml");
    FileInputStream inFile = null;

    inFile = new FileInputStream(aFile);

    FileChannel inChannel = inFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(48);

    while (inChannel.read(buf) != -1) {
      System.out.println("String read: " + ((ByteBuffer) (buf.flip())).asCharBuffer().get(0));
      buf.clear();
    }
    inFile.close();
  }
}

输出:

String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮

你错过了什么吗?谢谢,

大卫

4

1 回答 1

0

你应该试试这个

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 = "charData.xml";
        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();
            System.out.println("String read: ");
            CharBuffer chbuf = cs.decode(buf);
            for ( int i = 0; i < chbuf.length(); i++ ) {
                /* print each character */
                System.out.print(chbuf.get());
            }
            buf.clear();
        }
    }
}
于 2012-05-11T20:03:14.163 回答