爲什麼要將一個文件的內容複製到另一個文件中?爲什麼不使用操作系統來複制文件,或者使用Ruby的內置FileUtils.copy_file
?
ri FileUtils.copy_file
FileUtils.copy_file
(from ruby core)
------------------------------------------------------------------------------
copy_file(src, dest, preserve = false, dereference = true)
------------------------------------------------------------------------------
Copies file contents of src to dest. Both of src and
dest must be a path name.
更靈活/強大的替代方法是使用Ruby的內置FileUtils.cp
:
ri FileUtils.cp
FileUtils.cp
(from ruby core)
------------------------------------------------------------------------------
cp(src, dest, options = {})
------------------------------------------------------------------------------
Options: preserve noop verbose
Copies a file content src to dest. If dest is a
directory, copies src to dest/src.
If src is a list of files, then dest must be a directory.
FileUtils.cp 'eval.c', 'eval.c.org'
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
這幫助很大,謝謝您!我沒有考慮使用讀取方法。 – Mark 2011-05-15 00:30:58
我會非常小心使用這個解決方案,因爲它有可擴展性問題。 'IO#readlines'將整個文件整理到內存中。 – 2011-05-15 20:46:33