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 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.
File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With