2008-09-18 48 views
5

我有以下代码:阅读与FileChannel的ASCII文件和ByteArray对象

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

但字符获取在显示的。这是否与使用Unicode字符的Java有关?我该如何纠正?

回答

7

您必须知道文件的编码是什么,然后使用该编码将ByteBuffer解码为CharBuffer。假设文件是​​ASCII:

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

是的,它是Unicode。

如果你的文件中有14个字符,你只能得到7'?'。

解决方案未决。仍然在想。

1

是否有一个特定的原因,你为什么阅读文件的方式,你呢?

如果你正在阅读一个ASCII文件,你应该真的使用一个阅读器。

我会做类似:

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

,然后使用readLine或类似的数据,实际读取!

+1

我有大量的数据,我正在尝试优化阅读时间。参考:http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly – Jake 2008-09-18 15:23:37

+0

@Jake,在你的例子中你读取字节,然后解码为字符。为什么你认为这比使用BufferedReader更快?你指出的有趣的基准不读字符。 – 2010-03-16 20:49:28

2

改变你的print语句:

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

似乎帮助。

3

buf.getChar()期待每个字符2个字节,但你只储存1.使用:

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

你忘记修改代码,它仍然读取.get() – 2008-09-18 15:29:21

2

根据somefile.txt的编码,字符实际上可能没有两个字节组成。 This page提供了有关如何使用正确编码读取流的更多信息。

糟糕的是,文件系统并没有告诉你该文件的编码,因为它不知道。就它而言,它只是一堆字节。您必须找到某种方式将编码传递给程序,以某种方式检测它,或者(如果可能)始终确保编码是相同的(例如UTF-8)。