Create whole path automatically when writing to a new file
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Create whole path automatically when writing to a new file with sub folders
You need to create directory first then create file:
Like this:
String dirName = "/" + localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File file = new File(dirName);
file.mkdirs();
file = new File(file.getAbsolutePath()+"/quriReport.pdf");
file.createNewFile();
If you go your project directory you see 2018/August/quriReport.pdf
But IDE
show subfolder with .
if there is only one subfolder
.
Create a directory if it does not exist and then create the files in that directory as well
This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp()
and getClassName()
will work. You should also do something with the possible IOException
that can be thrown when using any of the java.io.*
classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id
is of type String
- I don't know as your code doesn't explicitly define it. If it is something else like an int
, you should probably cast it to a String
before using it in the fileName as I have done here.
Also, I replaced your append
calls with concat
or +
as I saw appropriate.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the /
in the filenames. For full portability, you should probably use something like File.separator to construct your paths.
Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir()
call will return true
if it created a directory, and false
if it didn't, including the case when the directory already existed.
Setting a path when creating a new File in Java
You can use System.getProperty(String)
to get the user.home
System Property. Then, use that to get the Desktop
. Finally, use that to get your desired output File
. Something like,
String homeFldr = System.getProperty("user.home");
File desktop = new File(homeFldr, "Desktop");
ImageIO.write(imageBlue, "PNG", new File(desktop, "imageBlue.PNG"));
Automatically creating directories with file output
In Python 3.2+, using the APIs requested by the OP, you can elegantly do the following:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
With the Pathlib module (introduced in Python 3.4), there is an alternate syntax (thanks David258):
from pathlib import Path
output_file = Path("/foo/bar/baz.txt")
output_file.parent.mkdir(exist_ok=True, parents=True)
output_file.write_text("FOOBAR")
In older python, there is a less elegant way:
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
How to automatically create whole path when creating new file using vim?
Try the plugin auto_mkdir. It sounds exactly what you are searching for.
PS: I don't have used it, and I will not (due to the comment of @Aaron_Digulla
To create a new directory and a file within it using Java
Basically, what's happening is, you are creating a directory called Library\test.txt
, then trying to create a new file called the same thing, this obviously isn't going to work.
So, instead of...
File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();
Try...
File file = new File("Library\\test.txt");
file.getParentFile().mkdir();
file.createNewFile();
Additional
mkdir
will not actually throw any kind of exception if it fails, which is rather annoying, so instead, I would do something more like...
File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
file.createNewFile();
} else {
throw new IOException("Failed to create directory " + file.getParent());
}
Just so I knew what the actual problem was...
Additional
The creation of the directory (in this context) will be at the location you ran the program from...
For example, you run the program from C:\MyAwesomJavaProjects\FileTest
, the Library
directory will be created in this directory (ie C:\MyAwesomJavaProjects\FileTest\Library
). Getting it created in the same location as your .java
file is generally not a good idea, as your application may actually be bundled into a Jar later on.
Create file in Java with all parent folders
You can ensure that parent directories exist by using this method File#mkdirs()
.
File f = new File("D:\\test3\\ts435\\te\\util.log");
f.getParentFile().mkdirs();
// ...
If parent directories don't exist then it will create them.
C++17 create directories automatically given a file path
You can use this function:
bool CreateDirectoryRecuresive(const std::string & dirName)
{
std::error_code err;
if (!std::experimental::filesystem::create_directories(dirName, err))
{
if (std::experimental::filesystem::exists(dirName))
{
return true; // the folder probably already existed
}
printf("CreateDirectoryRecuresive: FAILED to create [%s], err:%s\n", dirName.c_str(), err.message().c_str());
return false;
}
return true;
}
(you can remove the experimental
part if you have new enough standard library).
Documnetation for the methods used in the code:
std::filesystem::create_directories
.std::filesystem::exists
.
Related Topics
How to Configure Httponly Cookies in Tomcat/Java Webapps
When Should an Illegalargumentexception Be Thrown
Waiting at Sun.Misc.Unsafe.Park(Native Method)
How to Solve the "A Generic Array of T Is Created for a Varargs Parameter" Compiler Warning
What Is Mutex and Semaphore in Java? What Is the Main Difference
How to Get the Count of Line in a File in an Efficient Way
How to Convert Double[] to Double[]
How to Retrieve Ip Address from Http Header in Java
Generating Rsa Keys in Pkcs#1 Format in Java
How to Get the Http Status Code Out of a Servletresponse in a Servletfilter
Does Java Have Any Mechanism for a Vm to Trace Method Calls on Itself, Without Using Javaagent, etc
Java Io Ugly Try-Finally Block
How to Achieve Conditional Resource Import in a Spring Xml Context