【问题标题】:Using InputStream and InputStreamReader at the same time in javajava中同时使用InputStream和InputStreamReader
【发布时间】:2016-06-18 11:34:57
【问题描述】:

我从一个文件中创建了一个 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;
            }
        }
    } 
}

这是读取混合了字符和字节数据的文件的安全方法吗?

【问题讨论】:

    标签: java file inputstream fileinputstream


    【解决方案1】:

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

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

    【讨论】:

    • 不要使用DataInputStreamreadLine(),因为它自JDK 1.1起被标记为已弃用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2013-08-04
    相关资源
    最近更新 更多