How to create a new file together with missing parent directories? - java

When using
file.createNewFile();
I get the following exception
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
I am wondering is there a createNewFile that creates the missing parent directories?

Have you tried this?
file.getParentFile().mkdirs();
file.createNewFile();
I don't know of a single method call that will do this, but it's pretty easy as two statements.

As of java7, you can also use NIO2 API:
void createFile() throws IOException {
Path fp = Paths.get("dir1/dir2/newfile.txt");
Files.createDirectories(fp.getParent());
Files.createFile(fp);
}

Jon's answer works if you are certain that the path string with which you are creating a file includes parent directories, i.e. if you are certain that the path is of the form <parent-dir>/<file-name>.
If it does not, i.e. it is a relative path of the form <file-name>, then getParentFile() will return null.
E.g.
File f = new File("dir/text.txt");
f.getParentFile().mkdirs(); // works fine because the path includes a parent directory.
File f = new File("text.txt");
f.getParentFile().mkdirs(); // throws NullPointerException because the parent file is unknown, i.e. `null`.
So if your file path may or may not include parent directories, you are safer with the following code:
File f = new File(filename);
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();

Related

Create file in Java with all parent folders [duplicate]

This question already has answers here:
How to create a new file together with missing parent directories?
(3 answers)
Closed 3 years ago.
In java any way to create a file without its parent foler and parent's parent folder
Here is the full path of the file to be created.D:\test3\ts435\te\util.log
There is not any folder existing in this path, which means there is nothing under D:\.
In java, when I create this file
File testFile=new File(filePath);
testFile.createNewFile();
It says it cannot find the path. Then I try to create the parent folder 'te'. Then it fail again, saying it cannot find the parent folder 'ts435'.
Is there any way to create the file forcely? To create the file with or without its parents and upper level folders exist.
Update 2019-06-28:
Hi guys, I finally find the reason. There are two mehtods, mkdir() and mkdirs(). When the destination folder's parent folder not exist, mkdir() will return false because it cannot forcely build the entire folder struncture.
However, mkdirs() can do this magic. It can build the entire folder chain whether parent folder exist or not.
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.
File testFile=new File("D:\\test3\\ts435\\te\\util.log");
if(! testFile.getParentFile().exists()) {
testFile.getParentFile().mkdirs();
}
testFile.createNewFile();
You can use following method to create file and directory together.
public static String createFile(String filePath, String fileName) throws BotServiceException {
File directory = new File(filePath);
if (!directory.exists() && !directory.mkdirs()) {
throw new Exception("Directory does not exist and could not be created");
}
File newFile = new File(filePath+ File.separator + fileName);
boolean isSuccess = newFile.createNewFile();
return newFile.getAbsolutePath();
}

How to link a local file

I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post

Java, create a file and a folder

I am creating files with Java in Windows. This works:
String newFile = "c:/"+Utilities.timeFormat();
...
some code that creates a folder
This does not work:
String newFile = "c:/newDirectory/"+Utilities.timeFormat();
...
some code that creates a folder
You have to use File.mkdir() or File.mkdirs() method to create a folder.
EDIT:
String path="c:/newDirectory";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + Utilities.timeFormat());
if(file.createNewFile())
{
}
without knowing your actual code which is creating the directory:
use mkdirs() instead of mkdir()
Can you check that you have permissions to create a folder in c:/?
Can you show us the stacktrace too?
If "newDirectory" doesn't exist yet, you should use the method mkdirs() from the File class to create all the directories in between.
The fact that the directory doesn't exist is probably why it isn't working he first time through. As many have pointed out use mkdirs() will ensure if the file you want to write is in subfolders it will create them. Now here is what it might look like:
File file = new File( new File("c:/newDirectory"), Utilities.timeFormat() );
if( !file.getParentFile().exists() ) {
file.getParentFile().mkdirs();
}
OutputStream stream = new BufferedOutputStream( new FileOutputStream( file ) );
try {
// put your code here to write the file
} finally {
stream.close();
}
Notice I'm not using + to create a path. Instead I create a File object, and pass it the parent File and the name of the file. Also notice I'm not putting path separators in between the parent and filename. Using the File constructor takes care of a system independent way of creating paths.

Create File object of file from parent directory in java

I have this issue of accessing a file in one of the parent directories.
To explain, consider the following dir structure:-
C:/Workspace/Appl/src/org/abc/bm/TestFile.xml
C:/Workspace/Appl/src/org/abc/bm/tests/CheckTest.java
In the CheckTest.java I want to create a File instance for the TestFile.xml
public class Check {
public void checkMethod() {
File f = new File({filePath value I want to determine}, "TestFile.xml");
}
}
I tried a few things with getAbsolutePath() and the getParent() etc but was getting a bit complicated and frankly I think I messed it up.
The reason I don't want to use "C:/Workspace/Appl/src/org/abc/bm" while creating the File instance is because the C:/Workspace/Appl is not fixed and in all circumstances will be different at runtime and basically I don't want to hard-code.
What could be the easiest and cleaner way to achieve this ?
Thank you.
You should load it from Classpath in this case.
In your CheckTest.java, try
FileInputStream fileIs = new FileInputStream(CheckTest.class.getClassLoader().getResourceAsStream("org/abc/bm/TestFile.xml");
Use System.getProperty to get the base dir or you set the base.dir during application launch
java -Dbase.dir=c:\User\pkg
System.getProperty("base.dir");
and use
System.getProperty("file.separator");
What could be the easiest and cleaner way to achieve this ?
For accessing static resources use:
URL urlToResource = this.getClasS().getResource("path/to/the.resource");
If the resource is expected to change, write it to a sub-directory of user.home, where it is easy to locate later.
First of all, you can't get a reference to the source file path on runtime.
But, you can access the resrources included at your classpath (where you complied .class files will be).
Normally, your compiler will copy the xml file included at your srouce directory into the build directory, so at last, you could end up having something like this:
C:/Workspace/Appl/classes/org/abc/bm/TestFile.xml
C:/Workspace/Appl/classes/org/abc/bm/tests/CheckTest.class
Then, with your classpath pointing to the compiled classes root dir, you get the resources from this directory, using the ClassLoader.getResource method (or the equivalent Class.getResource() method).
public class Check {
public void checkMethod() {
java.net.URL fileURL=this.getClass().getResource("/org/abc/bm/tests/TestFile.xml");
File f=new File( fileURL.toURI());
}
}
One could do this:
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File file = new File(pathOfTheCurrentClass + "/..", "Testfile.xml");
or
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File filePath = new File(pathOfTheCurrentClass);
File file = new File(filePath.getParent(), "Testfile.xml");
But as Tomas Naros points out this gives you the file located in the build path.
Did you try
URL some=Test.class.getClass().getClassLoader().getResource("org/abc/bm/TestFile.xml");
File file = new File(some.getFile());

FileNotFound exception when trying to write to a file

OK, I'm feeling like this should be easy but am obviously missing something fundamental to file writing in Java. I have this:
File someFile = new File("someDirA/someDirB/someDirC/filename.txt");
and I just want to write to the file. However, while someDirA exists, someDirB (and therefore someDirC and filename.txt) do not exist. Doing this:
BufferedWriter writer = new BufferedWriter(new FileWriter(someFile));
throws a FileNotFoundException. Well, er, no kidding. I'm trying to create it after all. Do I need to break up the file path into components, create the directories and then create the file before instantiating the FileWriter object?
You have to create all the preceding directories first. And here is how to do it. You need to create a File object representing the path you want to exist and then call .mkdirs() on it. Then make sure you create the new file.
final File parent = new File("someDirA/someDirB/someDirC/");
if (!parent.mkdirs())
{
System.err.println("Could not create parent directories ");
}
final File someFile = new File(parent, "filename.txt");
someFile.createNewFile();
You can use the "mkdirs" method on the File class in Java. mkdirs will create your directory, and will create any non-existent parent directories if necessary.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29

Categories