2012-02-13 41 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