Java, create a file and a folder - java

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.

Related

create bunch of files in particular directory

I am trying to create lot of files in particular directory. If directory doesn't exist then it should create the directory and create bunch of files in it.
Whereever my program is running, it should create a "files" directory if it is not there and inside this "files" folder, I want to create bunch of files in it.
I have my below code but it looks like it is creating bunch of folders instead of one folder and all the files in that folder. What wrong I am doing?
for (Entry<String, String> entry : tasks.entrySet()) {
// looks like something is wrong here but can't figure out what wrong I am doing?
File file = new File("files/" + entry.getKey());
file.mkdirs();
try (BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),
StandardCharsets.UTF_8))) {
writer.write(entry.getValue());
} catch (IOException ex) {
// log error
}
}
For example, you're trying to create file C:\Stuff\Things\other.txt
With your current code, you create the folder C:\Stuff\Things\other.txt\
When you attempt to write to the file, moo.txt, it cannot, because you put a folder there (...\other.txt\)
Instead, create the folders up to, but not including the file name, before writing your file (C:\Stuff\Things\)
File file = new File(...);
file.getParentFile().mkdirs();
try(BufferedWriter ...

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

Java: How to create a new folder in Mac OS X

I want to create a folder in ex. my desktop in Mac OS X
I try to use this code, instead of Mymac is my name of course:)
String path="/Users/Mymac/Desktop";
String house = "My_home";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + house);
try {
if(file.createNewFile())
{
}
} catch (IOException ex) {
ex.printStackTrace();
}
Do you know how I could create a new folder?
And another thing is when I want to create a folder in the directory where my code is, do you know how I could write that? I have tried
String path="./";
String path="::MyVolume";
String path=".";
A platform-independent way:
File rootDir = File.listRoots()[0];
File dir = new File(new File(new File(rootDir, "Users"), "Mymac"), "Desktop");
if (!dir.exists()){
dir.mkdirs();
}
Your code is ok and will work. Perhaps you have a typo in your username in your file-path ("Mymac"), so you don't see the changes, since they go to another folder.
Running this code on my machine works fine and gives the expected result.
To make your code platform-independant, you can build your file-path with the following trick:
File path = new File(File.listRoots()[0], "Users" + System.getProperty("file.separator") + "Mymac" + System.getProperty("file.separator") + "Desktop"));
If "My_home" should be a folder and not a file, you have to change the file.createNewFile() - command. More detailed information you'll find in the answer of Thomas.
To find the folder/directory where one of your classes is (assuming they are not in a Jar), and then to create a subfolder there:
String resource = MyClass.class.getName().replace(".", File.separator) + ".class";
URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);
String path = new File(fileURL.toURI()).getParent();
String mySubFolder = "subFolder";
File newDir = new File(path + File.separator + mySubFolder);
boolean success = newDir.mkdir();
(The code above could be made more compact, I listed it more verbosely to demonstrate all the steps.) Of course, you need to be concerned about permission issues. Make sure that the user which is running java has permission to create a new folder.
Use file.mkdir() or file.mkdirs() instead of file.createNewFile() and it should work, if you have permission to create new folders and files.
mkdirs() will create the subfolders if they don't exist, mkdir() won't.
To create a directory in your base directory (the one you start your application from), just provide a relative path name: new File("mydir").mkdir();
Edit: to make file handling easier, I'd suggest you also have a look at Apache Commons' FilenameUtils and FileUtils.

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

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();

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