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



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

你在这里错过了什么吗?谢谢

大卫

你应该试试这个

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

最新更新