2012-05-11 62 views
0

我正在嘗試使用文件通道來讀取一個大型的xml文件,這裏的示例代碼我發現​​3210。當我嘗試它時,它打印出不可識別的字符: 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: ⸮ 

你錯過了什麼嗎? 謝謝,

大衛

回答

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

這個作品,謝謝!另一個問題:這裏的字節大小是否重要。如果我增加它會提高性能嗎? –

+0

實際上,它在某種意義上沒有更多無法識別的字符,但它不是按行讀取文件行 –

+0

@DavidZhao但問題是爲什麼它返回垃圾字符,我已經解決了。 –