回答
這裏是這樣做,使用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?
來檢查文件是否存在與否。這將返回一個布爾值,如果它真的!
爲謹慎起見,我建議使用緩衝區,除非你能保證整個文件總是裝入內存:
File.open("source", "rb") do |input|
File.open("target", "wb") do |output|
while buff = input.read(4096)
output.write(buff)
end
end
end
+1非常正確。即使在當今世界有多GB的RAM,重要的是要注意拉入的數量。沒有什麼比試圖讀取比可用內存更大的文件後讓大型服務器跪下。在企業中很難捍衛這種行爲。我建議使用嵌套的'File.open'塊來自動關閉文件。 –
爲什麼不使用'open'的塊版本來確保即使在異常情況下文件也被關閉了? – qerub
@Qerub因爲它取決於你將如何處理這種異常。關閉流並不總是正確的做法,尤其是當兩個文件受到影響時。 –
這裏有一個快速和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(文本被複制到)。
這裏我實現
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
對於那些有興趣,這裏的IO#copy_stream
,File#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
只是評論'b'表示'binmode'([二進制文件模式](https://ruby-doc.org/core-2.2.0/IO.html#method-c-new-label-IO+Open +模式))。 – Alex
- 1. 如何將文件內容複製到另一個文件?
- 2. 將img文件的內容複製到另一個img文件
- 3. 反覆將一個文件的內容複製到另一個文件
- 4. 複製逆向一個文件的內容複製到另一個文件
- 5. 在C++中將一個文件的內容複製到另一個文件中
- 6. 將一個excel文件內容複製到另一個excel文件的末尾
- 7. 使用read(),write(),open()將文件的內容複製到另一個文件
- 8. 將一個文件的內容移動到另一個文件
- 9. C - 將一個文件夾內容複製到另一個
- 10. Gulp將內容從一個文件複製到另一個文件
- 11. 將許多文件的內容複製到一個文件
- 12. 使用vbscript將文件從一個文件夾複製到另一個文件
- 13. 複製文件內容到另一個文件
- 14. 如何將文件從一個文件夾複製到另一個文件夾
- 15. 將文本文件內容複製到另一個文本文件
- 16. 將一個文件的內容複製到另一個文件中,排除幾個文件
- 17. 將x文件從一個文件夾複製到另一個
- 18. 將一個文件複製到另一個文件(Unix/C)?
- 19. 將png文件從一個文件夾複製到另一個
- 20. 將文件的一部分複製到另一個文件
- 21. XML:如何將一個xml文件的內容加載到另一個文件
- 22. Maven插件:將文件內容複製到另一個文件中
- 23. 複製文本文件的內容並將其複製到另一個
- 24. 如何將文件列表複製到另一個文件?
- 25. 如何將音頻文件複製到另一個文件
- 26. 複製一個文件到另一個內容保持其他文件空
- 27. 複製內容到同一個文件
- 28. 如何將一個xml文件的內容複製到Grails中的另一個文件中?
- 29. 從一個文件到另一個文件的高效複製
- 30. ROBOCOPY - 文件夾的內容複製到一個文件夾
你可能會解釋'script = $ 0'的用途,它也可以防止讀取大於內存的文件。 –