Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file in a specified directory

Tags:

file-io

ruby

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

like image 734
bAN Avatar asked Sep 17 '12 13:09

bAN


People also ask

How do you create a file in a specific directory in Linux?

The easiest way to create a new file in Linux is by using the touch command. The ls command lists the contents of the current directory. Since no other directory was specified, the touch command created the file in the current directory.

How do I save a file to a specific directory in Java?

File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();


1 Answers

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
like image 189
Lee Jarvis Avatar answered Sep 22 '22 23:09

Lee Jarvis