2016-03-04 61 views
1

我从文件和InputStreamReader中创建了一个InputStream对象。在java中同时使用InputStream和InputStreamReader

InputStream ips = new FileInputStream("c:\\data\\input.txt"); 
InputStreamReader isr = new InputStreamReader(ips); 

我将基本读以字节形式的数据到缓冲器,但是当有来自时我应该在字符读我将“开关模式”并用的InputStreamReader

读取时间
byte[] bbuffer = new byte[20]; 
char[] cbuffer = new char[20]; 

while(ips.read(buffer, 0, 20)!=-1){ 
    doSomethingWithbBuffer(bbuffer); 
    // check every 20th byte and if it is 0 start reading as char 
    if(bbuffer[20] == 0){ 
     while(isr.read(cbuffer, 0, 20)!=-1){ 
      doSomethingWithcBuffer(cbuffer); 
      // check every 20th char if its # return to reading as byte 
      if(cbuffer[20] == '#'){ 
       break; 
      } 
     } 
    } 
} 

是这是一种安全的方式来读取具有混合字符和字节数据的文件?

回答

2

不,这是不安全的。 InputStreamReader可能会从基础流(它使用内部缓冲区)中读取“太多”数据并破坏您从底层字节流读取的尝试。如果你想混合阅读字符和字节,你可以使用类似DataInputStream的东西。

或者,只读取字节数据并使用正确的字符编码将这些字节转换为字符/字符串。

+0

不要使用'DataInputStream'' readLine()',因为它自JDK 1.1开始被标记为弃用 – Kalsan

相关问题