I am trying to delete all files in a folder:-
import java.io.*;
public class AddService {
public static void main(String args[]){
File folder=new File("inputs");
File[] listOfFiles=folder.listFiles();
for(File file:listOfFiles){
if(file.delete())
System.out.println("File deleted");
else
System.out.println("File not deleted");
}
}
}
I am getting response "File not deleted" and the file isn't getting deleted. What's wrong with my code?
There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.
Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File in the first place.
Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.
Use Path and Files; you'll be glad you did.
Try giving the full path in this statement: "File folder=new File("inputs");"
Use try-catch block and print the exception, if any
I figured it out, I was using a FileReader to read contents of the file which I didn't close. Sorry for not providing the entire code
Java library delete function does not delete a directory if its not empty.
Try recursion over that to delete all sub-directories and files.
OR use some external library like apache commons io
File file = new File("/your/path/here");
FileUtils.deleteDirectory(file);
import org.apache.commons.io.FileUtils;
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version><!-- check latest version-->
</dependency>
Try calling Garbage Collector before deleting file.
EDIT: In think that file is being used by other processes while deleting and because of this you can't delete the file you want.
There is nothing wrong with your code except you should give the full path.
try this : File folder=new File("C:\\inputs");
instead of this line : File folder=new File("inputs");
You have not given the full path for the folder.
Also note to use forward slash.
try{
File folder=new File("C:/xxxx/xxxx/xxxx/inputs");
File[] listOfFiles=folder.listFiles();
for(File file:listOfFiles){
if(file.delete())
System.out.println("File deleted");
else
System.out.println("File not deleted");
}
}
catch(Exception e)
{
System.out.println(e.printStackTrace());
}
Always use try-catch for code that contains methods which throws Exceptions.
Related
I am creating comfort methods to delete files and dirs.
One of should delete all sub dirs and all files in a dir without deleting the dir itself.
In the unit test I create a structure like this
./SubDir2
./SubDir2/SubDir2SubDir1
fileToDeleteOnSubDir2SubDir1.txt
./SubDir2/SubDir2SubDir2
(contains no file)
So passing SubDir2 should delete both dirs and the file in them.
First I tried:
public static void deleteFilesAndSubDirsInDirectory(Path directory) throws TestException {
try {
Files.walk(directory)
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
throw new TestException("Could not delete all files and subdirectories in dir "
+ directory.getFileName()
+ ": " + e.getMessage());
}
}
When I pass subDir2, this deletes the file and SubDir2SubDir2. But not SubDir2SubDir1. Why? Path can be both file and directory??
Then I checked stackoverflow as usual found in Delete all files in directory (but not directory) - one liner solution
Arrays.stream(directory.toFile().listFiles()).forEach(File::delete);
which looked promising. But the result was worse:
When I pass subDir2 this deletes only SubDir2SubDir2.
SubDir2SubDir1 and its file remain.
I would like to understand better what's going wrong in these streams.
I wonder how to better test and debug streams as this is a kind of a black box thing leading to a lot of tries and errors.
Before I go back to plain old java it would be great if anybody would have a suggestion how to implement this method correclty using streams .
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.
I am trying to make this program that will write a file to the users computer but am having trouble really, I want to write a file called desktop.bat that I have to the c:/ directory but it doesn't seem like it's working. this is the code:
package javawriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaWriterObject {
public void TryThis(){
try{
File file = new File("C:\\Desktop.bat");
if (file.exists()){
System.out.println("The file exists \ndirectory is found");
}else{
System.out.println("file is not found yet ".concat("file will be created"));
file.createNewFile();
}
FileWriter out = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(out);
writer.write();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Do I have to write a String for the writer.write(); or can I do something where I can write the file I want instead?
Java 7's Files.copy method helps you copy a file from one location to another.
If you're using an older version of Java, you will need to either read the original file in yourself and copy its contents into your new file, or you'll have to use a third-party library. See the answers to this question for several good solutions, including using Apache Commons IO FileUtils or just the standard Java API.
Once you've decided how you want to copy the file, you might run into another problem. By default, Windows 7 will prevent you from writing to certain directories such as C:\. You can try writing to a different directory, such as in the temp directory or any location within the user's home directory. If you must write to C:\, the easiest solution (aside from creating the file ahead of time in Windows and overwriting it in your program, which probably defeats the purpose) is to disable UAC and make sure your user account has write permission on that directory--but this, of course, has security implications.
You have to get the content you want to write from somewhere, either a String literal in your application, or, the preferred method would be from a resource (bundled along with your application) via. YourClass.class.getResourceAsStream(name).
Copying an input stream to a file is a bit of effort, Guava can copy, but, if you're using Guava, you may as well copy directly from the resource to the file.
try{
private fileWriter= new PrintWriter(new FileWriter(file.txt));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
catch (IOException e){
e.printStackTrace();
} finally {
}
I have this text file in my source folder. So far, there haven't been any errors with accessing it. However, when I close the program or after when the files should have been written when I open the text file I don't find them there, however I did check the bin folder ocne and it seemed to print hello world to the temp copy there.
I want the changes it makes to be permanent.
You have a couple of problems in your code. Correcting/simplifying it to the following:
public static void main(String[] args) throws IOException {
PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("file.txt")));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
makes it create the file as expected. Try that out, and if it doesn't behave the way you're expecting, then explain how. Note that when you give a relative file path, it resolves the path against your current working directory. If the file is being written somewhere you don't expect, this is probably why.
The file in the bin folder is not a temp file, it is the file you are actually writing. If you want to write to the file in the source folder you have to use it's correct file path when opening the file for writing. Java always computes relative paths to the folder you started your application in. So your application is probably started in the bin folder and writes to file.txt there.
Maybe try using the append boolean in the FileWriter constructor
public FileWriter(String fileName, boolean append)
...and I think eclipse will use the bin folder as its default classpath so its no surprise the file is written there.
I hope that helps :)
Since the code was fine going to the package explorer --> project --> properties --> java build path --> source --> checking the box that says "allow outputs for source folders"