使用文件通道读取文本文件返回非法字符

时间:2012-05-11 19:52:23

标签: java file

我正在尝试使用文件通道来读取大型xml文件,这里是我找到的示例代码here。当我尝试它时,它会打印出无法识别的字符:     import java.io.File;     import java.io.File;     import java.io.FileInputStream;     import java.nio.ByteBuffer;     import 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: ⸮
你在这里错过了什么吗? 谢谢,

大卫

1 个答案:

答案 0 :(得分: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();
        }
    }
}