2012-02-13 44 views
3

运行下面的代码红宝石|为BinRead:无法分配内存(NoMemoryError)

 

    Dir.foreach(FileUtils.pwd()) do |f| 
     if f.end_with?('log') 
      File.open(f) do |file| 
       if File.size(f) > MAX_FILE_SIZE 
        puts f 
        puts file.ctime 
        puts file.mtime 

        # zipping the file 
        orig = f 
        Zlib::GzipWriter.open('arch_log.gz') do |gz| 
         gz.mtime = File.mtime(orig) 
         gz.orig_name = orig 
         gz.write IO.binread(orig) 
         puts "File has been archived" 
        end 

        #deleting the file 
        begin 
         File.delete(f) 
         puts "File has been deleted" 
        rescue Exception => e 
         puts "File #{f} can not be deleted" 
         puts "  Error #{e.message}"     
         puts "======= Please remove file manually ==========" 
        end 
       end 
      end 
     end 
    end 

而且文件是相当沉重超过1GB。任何帮助,将不胜感激。

回答

1

如果您正在阅读的文件> 1GB的,你必须有这么大的内存免费在最低限度,因为IO.binread是要发出声音的量。

你会更好加载已知量和循环的输入,直到它完全读取,读取和写入块。

从文档:

 
    IO.binread(name, [length [, offset]]) -> string 

------------------------------------------------------------------------------ 

Opens the file, optionally seeks to the given offset, then returns 
length bytes (defaulting to the rest of the file). binread ensures 
the file is closed before returning. The open mode would be "rb:ASCII-8BIT". 

     IO.binread("testfile")   #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n" 
     IO.binread("testfile", 20)  #=> "This is line one\nThi" 
     IO.binread("testfile", 20, 10) #=> "ne one\nThis is line " 
+0

我也看到了这个在docs,我想知道是否有另一种更类似于在.NET文件流,使红宝石不会不断创造文件句柄上每次调用binread。 – Candide 2012-02-13 08:49:51