2011-12-05 45 views

回答

0

這裏是這樣做,使用Ruby文件操作方法的簡單方法:

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() 

您還可以使用File.exists?來檢查文件是否存在與否。這將返回一個布爾值,如果它真的!

+3

你可能會解釋'script = $ 0'的用途,它也可以防止讀取大於內存的文件。 –

6

爲謹慎起見,我建議使用緩衝區,除非你能保證整個文件總是裝入內存:

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

+1非常正確。即使在當今世界有多GB的RAM,重要的是要注意拉入的數量。沒有什麼比試圖讀取比可用內存更大的文件後讓大型服務器跪下。在企業中很難捍衛這種行爲。我建議使用嵌套的'File.open'塊來自動關閉文件。 –

+0

爲什麼不使用'open'的塊版本來確保即使在異常情況下文件也被關閉了? – qerub

+0

@Qerub因爲它取決於你將如何處理這種異常。關閉流並不總是正確的做法,尤其是當兩個文件受到影響時。 –

18

有這個一個非常方便的方法 - 在IO#copy_stream method - 見ri copy_stream

輸出

用法示例:

+0

爲什麼不使用'open'的塊版本來確保即使在異常情況下文件也被關閉? – qerub

+0

更好:爲什麼不使用'File.write('src.txt',「某些文本\ n」)? – DNNX

+0

@DNNX從文檔中,'File.write'寫入'string'。如果內容不是純文本文件(如圖像),則不起作用。您必須改用'binread'和'binwrite'。 – Alex

1

這裏有一個快速和c用一種方法來做到這一點。

# 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) } 

運行這個的一個例子是。

$ ruby this_script.rb from_file.txt to_file.txt 

這將運行this_script.rb並通過命令行發生在兩個參數。在我們的情況下,第一個是 from_file.txt(文本被複制),第二個參數second_file.txt(文本被複制到)。

3

這裏我實現

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 

用法:

File.copy sourcepath, targetpath 
8

對於那些有興趣,這裏的IO#copy_streamFile#open + block答案(S)的變化(書面反對紅寶石2.2.x中,3太晚了)。

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 
+1

只是評論'b'表示'binmode'([二進制文件模式](https://ruby-doc.org/core-2.2.0/IO.html#method-c-new-label-IO+Open +模式))。 – Alex

0

您可以使用File.binread,如果你想守住了一下文件內容File.binwrite。 (其他答案使用即時copy_stream代替。)

如果內容比純文本文件,如圖像其他,使用基本File.readFile.write將無法​​正常工作。

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

來源:binreadbinwrite

相關問題