How to copy the contents of one file to another using Ruby methods?

I want to copy the contents of one file to another using Ruby file methods.

How can I do this with a simple Ruby program using file methods?

+8
ruby
source share
7 answers

Here is an easy way to do this using ruby ​​file methods:

source_file, destination_file = ARGV script = $0 input = File.open(source_file) data_to_copy = input.read() # gather the data using read() method puts "The source file is #{data_to_copy.length} bytes long" output = File.open(destination_file, 'w') output.write(data_to_copy) # write up the data using write() method puts "File has been copied" output.close() input.close() 

Can you also use File.exists? to check for a file or not. This will return a boolean true if it succeeds !!

0
source share

There is a very convenient way for this - IO#copy_stream method - to see the output ri copy_stream

Usage example:

 File.open('src.txt') do |f| f.puts 'Some text' end IO.copy_stream('src.txt', 'dest.txt') 
+18
source share

For those of interest to you, here is the answer option IO#copy_stream , File#open + block (written against ruby ​​2.2.x, 3 years later).

 copy = Tempfile.new File.open(file, 'rb') do |input_stream| File.open(copy, 'wb') do |output_stream| IO.copy_stream(input_stream, output_stream) end end 
+8
source share

As a precaution, I would recommend using a buffer if you cannot guarantee that the entire file is always stored in memory:

  File.open("source", "rb") do |input| File.open("target", "wb") do |output| while buff = input.read(4096) output.write(buff) end end end 
+6
source share

Here is my implementation

 class File def self.copy(source, target) File.open(source, 'rb') do |infile| File.open(target, 'wb') do |outfile2| while buffer = infile.read(4096) outfile2 << buffer end end end end end 

Using:

 File.copy sourcepath, targetpath 
+3
source share

Here is a quick and concise way to do this.

 # Open first file, read it, store it, then close it input = File.open(ARGV[0]) {|f| f.read() } # Open second file, write to it, then close it output = File.open(ARGV[1], 'w') {|f| f.write(input) } 

An example to run this would be.

 $ ruby this_script.rb from_file.txt to_file.txt 

This_script.rb is executed and takes two arguments through the command line. The first in our case is from_file.txt (the text is copied), and the second argument is second_file.txt (the text is copied to).

+1
source share

You can also use File.binread and File.binwrite if you want to save the contents of the file a bit. (In other answers, use instant copy_stream .)

If content other than text files , for example, images using the main File.read and File.write will not work.

 temp_image = Tempfile.new('image.jpg') actual_img = IO.binread('image.jpg') IO.binwrite(temp_image, actual_img) 

Source: binread , binwrite .

0
source share

All Articles