質問

私は、以下のコード:

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

その文字を取得し表示されますか?'s.せいてはJavaを使用Unicode文字?い正しいのか。

役に立ちましたか?

解決

いうファイルのエンコーディングは、デコードのByteBufferは、CharBufferを使用するエンコーディングです。を想定したファイルはアスキー:

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

他のヒント

buf.getChar()は2バイト文字だけの保管は1.用途:

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

変更する印刷述:

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

いるようです。

によってエンコードのsomefile.txtキャラクターが実際に構成することの二つのバイトです。 このページ される情報の読み方の流れに適切なエンコーディングです。

のbummerは、ファイルシステムのないファイルのエンコーディングで知らない.との関係をかけて食べるという習慣があり束のバイトです。まなければならないものコミュニケーションツールのエンコードのプログラムを検出すか、または(可能な場合)を常に確実にエンコードは同じです(UTF-8)。

ある特定の理由は、ファイルの読み取りの方がいましたか?

だ読ASCIIファイルばねを使用する。

思うようなもの:

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

そしていずれかを使用 readLine または類似のを実際に読み込みに!

あります。

まして14文字数にファイルから7'?'.

溶液中です。まだ考え方です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top