我正在尝试写入子目录内的文件。这个文件是由代码创建的,但是,一旦创建了这个文件,在脚本执行完成后,它是空的。我做错了什么?
# Creating output files
print "Creating output files and filling root menu..."
FileUtils.cd(outdir) do
file = File.new("directory.xml", "w")
file.puts "<?php header("Content-type: text/xml"); ?>"
file.puts "<CiscoIPPhoneMenu>"
file.puts "<Title>Telefonbuch</Title>"
file.puts "<Prompt>Dir External</Prompt>"
letters_used.each do |letter|
filename = "contacts_" + letter + ".xml"
FileUtils.touch(filename)
file.puts "<MenuItem>"
file.puts "<Name>" + letter.upcase + "</Name>"
file.puts "<URL>http://" + HOSTNAME + WEBSERV_DIR + "/" + filename + "</URL>"
file.puts "</MenuItem>"
end
file.puts "</CiscoIPPhoneMenu>"
file.rewind
end
print "Donen"
"directory.xml"应该链接到每个"contacts_letter.xml"文件,该文件也是由脚本创建的,但是directory.xml是空的。为什么?
习惯Ruby将使用块写入文件:
File.new("directory.xml", "w") do |fo|
fo.puts "<?php header("Content-type: text/xml"); ?>"
fo.puts "<CiscoIPPhoneMenu>"
fo.puts "<Title>Telefonbuch</Title>"
fo.puts "<Prompt>Dir External</Prompt>"
letters_used.each do |letter|
filename = "contacts_" + letter + ".xml"
FileUtils.touch(filename)
fo.puts "<MenuItem>"
fo.puts "<Name>" + letter.upcase + "</Name>"
fo.puts "<URL>http://" + HOSTNAME + WEBSERV_DIR + "/" + filename + "</URL>"
fo.puts "</MenuItem>"
end
fo.puts "</CiscoIPPhoneMenu>"
end
在文件块结束时自动关闭文件。