How to create a file in a directory in java?
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
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.
How to create a directory in Java?
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
Java - How to create a file in a directory using relative Path
File dir = new File("tmp/test");
dir.mkdirs();
File tmp = new File(dir, "tmp.txt");
tmp.createNewFile();
BTW: For testing use @Rule and TemporaryFolder class to create temp files or folders
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.
How to create a file -- including folders -- for a given path?
Use this:
File targetFile = new File("foo/bar/phleem.css");
File parent = targetFile.getParentFile();
if (parent != null && !parent.exists() && !parent.mkdirs()) {
throw new IllegalStateException("Couldn't create dir: " + parent);
}
While you can just do file.getParentFile().mkdirs()
without checking the result, it's considered a best practice to check for the return value of the operation. Hence the check for an existing directory first and then the check for successful creation (if it didn't exist yet).
Also, if the path doesn't include any parent directory, parent
would be null
. Check it for robustness.
Reference:
- File.getParentFile()
- File.exists()
- File.mkdir()
- File.mkdirs()
How to create a file in a folder in java
You can use mkdir()
method from File class:
new File("path\\School").mkdir();
FileWriter writer = new FileWriter("path\\School\\student.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Hello");
buffer.close();
Here path
need to be replaced with your system path for the .
How to create file in a project folder in Java?
In my project i created a "logs" folder outside the src folder with the file definition:
File file = new File("logs/file.txt");
So I expect you can create a file there with File("/file.txt")
Java - how do I write a file to a specified directory
Use:
File file = new File("Z:\\results\\results.txt");
You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.
For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.
File file = new File("/home/userName/Documents/results.txt");
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.
Related Topics
Why Does List<String>.Toarray() Return Object[] and Not String[]? How to Work Around This
Drawing in Jlayeredpane Over Exising JPAnels
How to Disable Jsessionid in Tomcat Servlet
How to Combine Two Hashmap Objects Containing the Same Types
Changing Swing Jtable Cell Colors
Jfreechart Series Tool Tip Above Shape Annotation
Issues with Swingworker and Jprogressbar
Code for Changing the Color of Subtasks in Gantt Chart
Struts 2:There Is No Action Mapped for Namespace [/]
Graphics Rendering in Title Bar
Adding Up Bigdecimals Using Streams
Differencebetween Class.This and This in Java