How can I create a new file in a specific directory. I created this class:
如何在特定目录中创建新文件。我创建了这个类:
class FileManager
def initialize()
end
def createFile(name,extension)
return File.new(name <<"."<<extension, "w+")
end
end
I would like to specify a directory (path) where to create the file. If this one doesn't exist, he will be created. So do I have to use fileutils
as shown here just after file creation or can I specify directly in the creation the place where create the file?
我想指定一个目录(路径)创建文件的位置。如果这个不存在,他将被创建。因此,我必须在文件创建后立即使用fileutils,或者我可以在创建中直接指定创建文件的位置吗?
Thanks
1 个解决方案
#1
26
The following code checks that the directory you've passed in exists (pulling the directory from the path using File.dirname
), and creates it if it does not. It then creates the file as you did before.
以下代码检查您传入的目录是否存在(使用File.dirname从路径中提取目录),如果不存在则创建它。然后它像以前一样创建文件。
require 'fileutils'
def create_file(path, extension)
dir = File.dirname(path)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
path << ".#{extension}"
File.new(path, 'w')
end
#1
26
The following code checks that the directory you've passed in exists (pulling the directory from the path using File.dirname
), and creates it if it does not. It then creates the file as you did before.
以下代码检查您传入的目录是否存在(使用File.dirname从路径中提取目录),如果不存在则创建它。然后它像以前一样创建文件。
require 'fileutils'
def create_file(path, extension)
dir = File.dirname(path)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
path << ".#{extension}"
File.new(path, 'w')
end