Create Directory along with file using file stream in java - 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();

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 ...

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

getResource() unable to read contents of a directory inside jar

I just came around this issue that the main class inside jar is unable to read the contents of a folder.
The class contains
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
try {
File file = new File(TestResources.class.getClassLoader()
.getResource(path).getPath());
System.out.println(file.exists());
} catch (Exception e) {
e.printStackTrace();
}
Here sysout returns false.
But when I try something like this it works
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
FileOutputStream out = null;
InputStream is = null;
try {
is = TestResources.class.getClassLoader().getResourceAsStream(path);
byte bytes[] = new byte[is.available()];
is.read(bytes);
out = new FileOutputStream("abc.jpg");
out.write(bytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
getResourceAsStream() is able to read the path of the folder inside jar but getResource() is unable to read it,
why is it so and what is the difference between the reading mechanism of these two methods for contents inside jar.
The contents of the simple jar
Both getResource() and getResourceAsStream() are able to find resources in jar, they use the same mechanism to locate resources.
But when you construct a File from an URL which denotes an entry inside a jar, File.exists() will return false. File cannot be used to check if files inside a jar/zip exists.
You can only use File.exists which are on the local file system (or attached to the local file system).
You need to use an absolute path to get the behavior you're expecting, e.g. /flowers/FL8-4_zpsd8919dcc.jpg, as sp00m suggested.

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.

File won't remove

I am trying to remove a file in java, but it will not remove. Could someone explain why it won't remove?
Here is the code that I am using:
File bellFile = new File("config\\normbells.txt");
bellFile.delete();
File bellFileNew = new File("config\\normbells.txt");
bellFileNew.createNewFile();
System.out.println("Done!");
NOTE: I am trying to wipe the file, if that helps.
File deletion can fail under the following circumstances:
The file does not exist.
The file is a directory not a file.
You don't have access to delete the file.
You don't have access to the the file or any of its parent directory.
The file is being used currently by some another application.
Try avoiding all the above mentioned circumstances & you'll surely able to delete the file.
Also before deleting the file add this condition :
if (file.exists()) {
file.delete();
}
Java7 has new functionality for this.
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.delete(target);
Path newtarget = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
= PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
Files.createFile(newtarget, attr);
Take a look at the File class http://docs.oracle.com/javase/7/docs/api/java/io/File.html
File bellFile = new File("config\\normbells.txt");
if(bellFile.delete())
{
System.out.println("Done!");
}

Categories