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

Также файлы довольно тяжелый более 1 Гб. Любая помощь будет оценена по достоинству.

ответ

1

Если файлы, которые вы читаете в> 1 Гб, вы должны иметь так много свободной памяти, как минимум, потому что 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

Я тоже видел это в документации, и мне было интересно, если есть альтернатива более похожа на файловых потоков .net, поэтому рубин не постоянно создавать дескрипторов файлов на каждый вызов binread. – Candide

Смежные вопросы