ruby 在Ruby中拆分和连接文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 在Ruby中拆分和连接文件相关的知识,希望对你有一定的参考价值。

require 'fileutils'

file_to_split        = '/home/ikon/tmp/talk.mkv'
output_path          = File.dirname file_to_split
split_file_base_name = File.basename file_to_split
chunks_in_bytes      = 5 * 1024 * 1024
read_buffer          = 256 * 1024

File.open file_to_split, 'rb' do |f|
  puts 'Start splitting'

  file_splits_created = 0
  until f.eof?
    file_splits_created += 1
    puts "Creating split no. #{file_splits_created}"
    generated_split_file_suffix = ".#{file_splits_created}"
    bytes_written               = 0
    begin
      split_file_name = "#{File.join(output_path, split_file_base_name)}.#{generated_split_file_suffix}"
      FileUtils.rm_f split_file_name
      split_file      = File.open split_file_name, 'ab'
      while bytes_written <= chunks_in_bytes and (data = f.read(read_buffer))
        print '.'
        split_file.write data
        bytes_written += read_buffer
      end
    rescue => e
      puts "EXCEPTION: #{e.message}"
      f.close
    ensure
      puts "\n" 'closing split file'
      split_file.close unless split_file.nil?
    end
  end

  puts 'splits created, closing main file'
end
require 'fileutils'

new_file_name = '/home/ikon/tmp/new_talk.mkv'
split_file_basename = '/home/ikon/tmp/talk.mkv'
read_buffer      = 256 * 1024

FileUtils.rm_f new_file_name
File.open new_file_name, 'ab' do |f|

  file_number = 0
  loop do
    file_number     += 1
    split_part_file = "#{split_file_basename}.#{file_number}"
    break unless File.exist? split_part_file

    puts "Reading split file no. #{file_number}"
    begin
      split_file = File.open split_part_file, 'rb'
      while (data = split_file.read(read_buffer))
        print '.'
        f.write data
      end
    rescue => e
      puts "EXCEPTION: #{e.message}"
      f.close
    ensure
      puts "\n" 'closing split file'
      split_file.close unless split_file.nil?
    end
  end

  puts 'file joined, closing'
end

以上是关于ruby 在Ruby中拆分和连接文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Ruby 中拆分分隔字符串并将其转换为数组?

ruby - 当值更改时将数组拆分为子数组并忽略/删除该值

RoR,Ruby 如何从数据库中拆分数据并使用计数

Ruby将数组拆分为X组

ruby 在Rails中将操作拆分为部件(批处理)

Ruby代码美化,多行拆分长指令