Рубин | binread: не удалось выделить память (NoMemoryError) - PullRequest
3 голосов
/ 13 февраля 2012

Выполнение следующего кода


    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 голос
/ 13 февраля 2012

Если файлы, которые вы читаете, имеют размер> 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 "
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...