在指定的目录下创建一个文件 [英] Create a file in a specified directory

查看:200
本文介绍了在指定的目录下创建一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在特定目录中创建新文件?我创建了这个类:

$ p $ class FileManager

$ initialize()

结束
$ b $ def createFile(名称,扩展名)
返回File.new(名称<<<<<扩展名,w +)
结束
end

我想指定一个目录(路径)在哪里创建文件。如果这个不存在,他将被创建。所以我必须使用 fileutils 如图所示这里就在文件创建之后,或者我可以直接在创建文件的地方创建文件?



谢谢

解决方案

以下代码检查您传入的目录是否存在(使用 File从路径中拉取目录。 dirname ),如果没有则创建它。然后创建文件,就像以前一样。

$ p $ require'fileutils'

def create_file(path ,扩展)
dir = File.dirname(路径)

除非File.directory?(dir)
FileUtils.mkdir_p(dir)
结束

路径<< 。#{extension}
File.new(path,'w')
end


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?

Thanks

解决方案

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.

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

这篇关于在指定的目录下创建一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆