Read binary file as string in Ruby

后端 未结 8 1564
无人共我
无人共我 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:30

    If you can encode the tar file by Base64 (and storing it in a plain text file) you can use

    File.open("my_tar.txt").each {|line| puts line}
    

    or

    File.new("name_file.txt", "r").each {|line| puts line}
    

    to print each (text) line in the cmd.

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

    First, you should open the file as a binary file. Then you can read the entire file in, in one command.

    file = File.open("path-to-file.tar.gz", "rb")
    contents = file.read
    

    That will get you the entire file in a string.

    After that, you probably want to file.close. If you don’t do that, file won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.

    0 讨论(0)
提交回复
热议问题