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 に答える