2013-02-05 50 views
0
DataOutputStream lWriter = new DataOutputStream(connection.getOutputStream()); 

    int bytesRead = 0; 
    int offset = 0; 
    byte[] bytes = new byte[1048576]; // read 1MB at a time 
    RandomAccessFile f = new RandomAccessFile(xmlFile, "rw"); 
    while(bytesRead != -1){ 
     offset += f.read(bytes, offset, bytes.length); 
     if (bytesRead != -1){ 
      lWriter.write(bytes, 0, bytes.length); 
     } 
} 

有了这段代码,我得到一个索引超出f.read()的界限异常。我可能错误地误用了参数偏移量和长度。我不会每次读到一个块时,都应该将偏移量移动到块的大小上?也许我只需要少阅读,并使用较小的缓冲区?有一个问题写入DataOutputStream和从缓冲区读RandomAccessFile

目前我有这个实现的工作,但我担心内存的使用:

DataOutputStream lWriter = new DataOutputStream(connection.getOutputStream());  
lWriter.write(fileToBytes(xmlFile)); 

感谢您的帮助!

回答

1

在Java中复制流的典型方法如下:

while ((count = in.read(buffer)) > 0) 
{ 
    out.write(buffer, 0, count); 
    // bytesRead += count; // if you are counting 
} 

你的循环包含了许多错误。偏移量是缓冲区中的偏移量,而不是文件,您几乎不必使用它。您不必提前抵消。您正在测试bytesRead,但从未在初始化后设置它。在推进计数之前,您没有检查EOS。写入时您没有使用读取计数,因此您正在向文件写入垃圾。