How do I create an empty folder in java? - java

The problem I am having is that when I attempt to create the folder, it doesn't create. It might have something to do with the directory, but honestly I don't know. I tried using this:
File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
try{
if(f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}
But it didn't work for me.
And this is the directory I put in the File, but I want the program to work on any computer: C:\Users\(My name)\Desktop\Levels\First Folder\Levels

You said only the Desktop directory exists, so you'll need to use mkdirs to construct the whole directory tree:
File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
try{
if(f.mkdirs()) { //< plural
System.out.println("Directory Created");
Keep in mind: you may want to check whether this directory exists before you try to create it, as it presumably isn't an error and is permissible to continue if your program has created it once before.

Recommending Files.createDirectories() instead of File.mkdirs() because handling errors is more straightforward.
Thus:
Files.createDirectories(Paths.get(System.getProperty("user.home"), "/Levels/First Folder/Levels"));
With mkdirs() it is difficult to determine if it failed, why it failed, or if it did not create the directory because it already existed.

Related

How can I move files to another folder with java?

I want to move files (images) from a folder to another:
For example:
/home/folder1/image.png
to
/home/folder1/folder2/image.png
And obviously remove the image from the folder1
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it.
I hope someone can help me a little with this, Thanks.
EDIT:
Well I can put the code but it's simple to explain what i did:
I just created a Folder class that has a File object of my folder (/home/folder1) , i read all the images inside and save it in an File array, then i scan it and try to change the path of every image file String to another
EDIT:
Thanks to all for the help, all are good examples, I was able to change my files to another location, there was a bunch of files I wanted to move so, I didn't want to create too many objects.
You said you tried renameTo and it didn't work, but this worked for me. After I renamed it I deleted the original file.
File a = new File("C:\\folderA\\A.txt");
a.renameTo(new File("C:\\folderB\\" + a.getName()));
a.delete();
In java 8+ you can simply use Files.move from nio:
try {
Path source = Paths.get("/home/folder1/image.png");
Path dest = Paths.get("/home/folder1/folder2/image.png");
Files.move(source, dest);
} catch (IOException e) {
...
}
The paths can even come from different file system providers (ie a ZipFileSystem).
Commons-io has a few methods in the FileUtils class that can help you.
http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html
Example:
FileUtils.moveFile(src, dest);
The usual approach to solving this is copying the file and then deleting it from the original location, but you can follow this tutorial for more information. Also, the platform(linux, windows, is not important).
I didn't run this, but it should work
File f1 = new File("/home/folder1/image.png");
File f2 = new File("/home/folder1/folder2/image.png");
f1.renameTo(f2);
There are many approaches for you to do that.
This snippet is one of them, you can move your files like this way:
try {
final File myFile = new File("C:\\folder1\\myfile.txt");
if(myFile.renameTo(new File("C:\\folder2\\" + myFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}

previous file deletion process

I am stuck up in a odd situation that is I am creating a file in a folder but I need to make sure that before the creation of a file if any file is there in the folder then it must be deleted only the current file which is process should be there.
since in my application every day a job runs which create the file in that folder so when ever presently job is running it should delete previous day file and no file should be there in afolder but the code that is shown below creates the file in that folder but the issue is that previous day file or if the job run multiple time on the same day also then those files are also thhere in the folder which should be deleted please advise how to achieve this..
File file = new File(FilePath + s); //path is c:\\abc folder & s is file name fgty.dat file
if (file.exists()) {
file.delete();
}
file.createNewFile();
Please advise
In your place I'd move the directory to a different name, say abc.OLD, recreate it and then create your file. If everything goes well, at the end you can remove the ols directory.
If different instances of your program could be running at the same time you need to implement some form of synchronization. A rather simplistic approach could be to check if the abc.OLD directory exists and abort execution if it does.
Without seeing more of your code, it sounds like you just need to empty the folder before opening a new file, since right now you're only deleting the file with the exact name that you're going to write. Use the list method of file objects.
File newFile = new File(FilePath + s);
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
f.delete();
}
newFile.createNewFile();
Note that this won't work if your folder contains other non-empty directories; you'll need a more robust solution. But the code above will at least delete all the files in the folder (barring Exceptions obviously) before creating the new file.
If, as you mentioned in the comments, you only want to delete *.dat files, it's as simple as putting a check in before you delete anything.
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
if (f.getName().endsWith(".dat")) { // Only delete .dat files
f.delete();
}
}
File file = new File(FilePath+"test.txt");
File folder = new File(FilePath);
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
listOfFiles[i].delete();
}
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
First I think you can have problems with the way you instanciate your Fileobject because if you don't have your path separator (\), you will try to create c:\abcfgty.dat instead of c:\abc\fgty.dat.
Use instead :
File file = new File(filePath, s);
Then you can delete the files ending by ".dat". As I understood, you don't need to delete sub directories. (Here is a link that tells you how. See also here)
for (File f : filePath.list()) { // For each file in the directory, delete it.
if(f.isFile() && file.getName().toLowerCase().endsWith(".dat");){
f.delete();
}
}
try {
file.createNewFile();
} catch (IOException ex) {
//Please do something here, at leat ex.printStackTrace()
}
Note that we can use a FileFilter to select the files to delete.
EDIT
As it was suggested in other answers, it might be preferable to move or rename the existing files instead of deleting them directly.

Create Directory along with file using file stream in java

I have a String like this "D:/Data/files/store/file.txt" now I want to check ,is directory is already exist or not, if not I want to create directory along with text file. I have tried mkdirs() but its creating directory like this data->files->store->file.txt. means its creates file.txt as folder, not a file. can any one kindly help me to do this. thanks in advance.
You need to run mkdirs() on parent directory, not the file itself
File file = new File("D:/Data/files/store/file.txt");
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Here you go...
boolean b = (new File("D:/Data/files/store/file.txt").getParentFile()).mkdirs();

File.createNewFile() thowing IOException No such file or directory

I have a method that writes to a log file. If the file exists it should append to it, if not then I want it to create a new file.
if (!file.exists() && !file.createNewFile()) {
System.err.println("Error with output file: " + outFile
+ "\nCannot create new file.");
continue;
}
I have that to check that a file can be created. file is a java.io.File object. createNewFile is throwing an IOException: No such file or directory. This method has been working perfectly since I wrote it a few weeks ago and has only recently starting doing this although I don't know what I could have changed. I have checked, the directory exists and I have write permissions for it, but then I thought it should just return false if it can't make the file for any reason.
Is there anything that I am missing to get this working?
try to ensure the parent directory exists with:
file.getParentFile().mkdirs()
Perhaps the directory the file is being created in doesn't exist?
normally this is something you changed recently, first off your sample code is if not file exists and not create new file - you are trying to code away something - what is it?
Then, look at a directory listing to see if it actually exists and do a println / toString() on the file object and getMessage() on the exception, as well as print stack trace.
Then, start from zero knowledge again and re factor from the get-go each step you are using to get here. It's probably a duh you stuck in there somewhere while conceptualizing in code ( because it was working ) - you just retrace each step in detail, you will find it.
I think the exception you get is likely the result from the file check of the atomic method file.createNewFile(). The method can't check if the file does exist because some of the parent directories do not exist or you have no permissions to access them. I would suggest this:
if (file.getParentFile() != null && !file.getParentFile().mkDirs()) {
// handle permission problems here
}
// either no parent directories there or we have created missing directories
if (file.createNewFile() || file.isFile()) {
// ready to write your content
} else {
// handle directory here
}
If you take concurrency into account, all these checks are useless because in every case some other thread is able to create, delete or do anything else with your file. In this case you have to use file locks which I would not suggest doing ;)
According to the [java docs](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createNewFile() ) createNewFile will create a new file atomically for you.
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
Given that createNewFile is atomic and won't over-write an existing file you can re-write your code as
try {
if(!file.createNewFile()) {
System.out.println("File already exists");
}
} catch (IOException ex) {
System.out.println(ex);
}
This may make any potential threading issues, race-conditions, etc, easier to spot.
You are certainly getting this Exception
'The system cannot find the path specified'
Just print 'file.getAbsoluteFile()' , this will let you know what is the file you wanted to create.
This exception will occur if the Directory where you are creating the file doesn't exist.
//Create New File if not present
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
Log.e(TAG, "File Created");
}
This could be a threading issue (checking and creating together are not atomic: !file.exists() && !file.createNewFile()) or the "file" is already a directory.
Try (file.isFile()) :
if (file.exists() && !file.isFile()){
//handle directory is there
}else if(!file.createNewFile()) {
//as before
}
In my case was just a lack of permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use
yourAppsMainActivityContext.getExternalCacheDir()
instead of
Environment.getExternalStorageDriectory()
to get the file storage path.
Alternatively, you can also try getExternalFilesDir(String type), getExternalCacheDir(), getExternalMediaDirs().

How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?
The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.
If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.
Using java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.
new File("path/to/file.txt").isFile();
new File("C:/").exists() will return true but will not allow you to open and read from it as a file.
By using nio in Java SE 7,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)
You can check if path is a directory or regular file.
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
Using Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
f.createNewFile();
So f.exists() can be used to check whether such a file exists or not.
f.isFile() && f.canRead()
There are multiple ways to achieve this.
In case of just for existence. It could be file or a directory.
new File("/path/to/file").exists();
Check for file
File f = new File("/path/to/file");
if(f.exists() && f.isFile()) {}
Check for Directory.
File f = new File("/path/to/file");
if(f.exists() && f.isDirectory()) {}
Java 7 way.
Path path = Paths.get("/path/to/file");
Files.exists(path) // Existence
Files.isDirectory(path) // is Directory
Files.isRegularFile(path) // Regular file
Files.isSymbolicLink(path) // Symbolic Link
Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
double the code
the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
You can use the following: File.exists()
first hit for "java file exists" on google:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.
Used the following snippet:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
The following snippet
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
From Java Oracle documentation
It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html
This has additional methods for managing files and often better than JDK.
Simple example with good coding practices and covering all cases :
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Reference and more examples at
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
You can make it this way
import java.nio.file.Paths;
String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
//...do somethinh
}
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
exists(): Tests whether the file or directory denoted by this abstract pathname exists.
docs.oracle.com
You must use the file class , create a file instance with the path of the file you want to check if existent . After that you must make sure that it is a file and not a directory . Afterwards you can call exist method on that file object referancing your file . Be aware that , file class in java is not representing a file . It actually represents a directory path or a file path , and the abstract path it represents does not have to exist physically on your computer . It is just a representation , that`s why , you can enter a path of a file as an argument while creating file object , and then check if that folder in that path does really exist , with the exists() method .
If spring framework is used and the file path starts with classpath:
public static boolean fileExists(String sFileName) {
if (sFileName.startsWith("classpath:")) {
String path = sFileName.substring("classpath:".length());
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
return (url != null);
} else {
Path path = Paths.get(sFileName);
return Files.exists(path);
}
}

Categories