Read binary file as string in Ruby

后端 未结 8 1563
无人共我
无人共我 2020-11-30 16:40

I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:

file = File         


        
相关标签:
8条回答
  • 2020-11-30 17:17

    You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

    You do something like:

    require 'base64'
    
    file_contents = Base64.encode64(tar_file_data)
    

    Have look at the Base64 Rubydocs to get a better idea.

    0 讨论(0)
  • 2020-11-30 17:19

    on os x these are the same for me... could this maybe be extra "\r" in windows?

    in any case you may be better of with:

    contents = File.read("e.tgz")
    newFile = File.open("ee.tgz", "w")
    newFile.write(contents)
    
    0 讨论(0)
  • 2020-11-30 17:20

    how about some open/close safety.

    string = File.open('file.txt', 'rb') { |file| file.read }
    
    0 讨论(0)
  • 2020-11-30 17:24

    If you need binary mode, you'll need to do it the hard way:

    s = File.open(filename, 'rb') { |f| f.read }
    

    If not, shorter and sweeter is:

    s = IO.read(filename)
    
    0 讨论(0)
  • 2020-11-30 17:24

    To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.

    contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }
    
    0 讨论(0)
  • 2020-11-30 17:30

    Ruby have binary reading

    data = IO.binread(path/filaname)
    

    or if less than Ruby 1.9.2

    data = IO.read(path/file)
    
    0 讨论(0)
提交回复
热议问题