I have written the following code to merge and delete the source files,but somehow the source files are not getting deleted.Can any one please throw some light on what i 'm missing here.
public void doDelete(List<String> dID)throws IOException {
String DID=null;
try{
for( ListIterator<String> iterator = dID.listIterator(); iterator.hasNext();)
{
DID= (String) iterator.next();
System.out.println("Deleting PDF" +DID);
File f =new File("E:\\TestFolder"+ "\\" +DID+".pdf");
if (!f.exists()) {
System.err.println("File " + f
+ " not present to begin with!");
return;
}
System.out.println(f.length());
System.out.println(f.getAbsolutePath());
boolean success = f.delete();
if (!success){
System.out.println("Deletion failed.");
}else{
System.out.println("File deleted."+DID);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
TL;DR but file deletion failures is usually due to the file still being open. Especially as you are running it on Windows.
If you would like to get a reason for the delete failure you can use the Java 7 file API instead, it will give you the deletion failure reason as an exception.
java.nio.Files.delete(...)
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#delete(java.nio.file.Path)
In your createFileFromBlob method you are opening multiple FileOutputStreams (for each element of dID.listIterator()) but only closing the last one in your finally block. This will leave an open handle to all files other than the last, preventing them from being deleted as per Pulsar's answer.
Related
Edit: I just found out that not a IOExcpetion but a FilerException is thrown. Therefore I changed that in the description and the title.
I'm working with Annotation Processing to generate some files for my java project. Now I always get an FilerException when the Annotation Processing tries to generate my files.
This is the way I create the files (GenClass and GenAnnotation are custom classes that abstract the generated classes. They weren't changed in about half a year so I'm sure the error isn't somewhere there. The way I write the files also didn't change in the last year.):
public static boolean generateJavaSourceFile(final ProcessingEnvironment processingEnv,
final GenClass element, final String fileName, final Class<?> generatorClass) {
boolean succeed = false;
Writer fw = null;
Filer f = processingEnv.getFiler();
// Mark the class as generated
GenAnnotation generatedAnnotation = getAnnotation(generatorClass);
element.pushImport(generatedAnnotation);
element.addAnnotation(generatedAnnotation);
try {
JavaFileObject jfo = f.createSourceFile(fileName, (Element[]) null);
// create new java source file
fw = jfo.openWriter();
// write the GenClass object into file
fw.write(element.toString());
succeed = true;
} catch (FilerException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
processingEnv.getMessager().printMessage(Kind.ERROR,
"Could not create source file " + fileName
+ " because it already exists");
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
throw new RuntimeException(e.getMessage(), e);
} finally {
if (fw != null) {
try {
fw.close(); // flush and close the stream
} catch (IOException e) {
LOGGER.severe("Couldn't close file [" + fileName + "]!");
}
}
}
LOGGER.fine(fileName + " written");
return succeed;
This is the message of the exception:
Source file already created: /path/to/the/file/to/create
I did change something on my processors, however the error only occurs for a certain type of files (Filters we use to filter data) and I didn't change anything on the processor that generates the filters. I added a new processor that works with a different annotation and those file are generated correctly.
Does anyone know what the cause of this error could be?
I had an error in another processor (that had nothing to do with the processor that generates the Filters) and that caused this error. Now that I fixed that error also this behavior stopped. I'm not really sure why this FilerException happened all the time, however it is gone now.
I am trying to delete a folder and its files in C:\Program Files\folder\files. I am not the creator of the folder but I do have admin rights in this very machine I am executing my java code. I am getting IO Exception error stating that I do not have permission to do this operation. So i tried PosixFilePermission to set permission which didn't work either. I have heard there is a workaround using bat or bash command to give admin privilege and execute the batch before deleting the folder. Please let me know if I am doing something wrong or advise on the best workaround.
Note: file.canWrite() didn't throw any exception while checking the
write access. I am using JDK 1.7
String sourcefolder = "C:\Program Files\folder\files";
File file = new File(sourcefolder);
try {
if (!file.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ sourcefolder);
file.setWritable(true, false);
//using PosixFilePermission to set file permissions 777
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OTHERS_WRITE);
Files.setPosixFilePermissions(Paths.get(sourcefolder), perms);
//file.delete();
FileUtils.cleanDirectory(file);
System.out.println("Deleted");
} catch (Exception e) {
e.printStackTrace();
}
You could be getting a failed delete for a number of reasons:- the file could be locked by the file system, you may lack permissions, or could be open by another process etc.
If you're using Java 7 or above you can use the javax.nio.* API; it's a little more reliable & consistent than the [legacy][1] java.io.Fileclasses;
Path fp = file.toPath();
Files.delete(fp);
If you want to catch the possible exceptions:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
This is my code to delete you can also refer this:-
import java.io.File;
class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("C:\\JAVA\\1.java");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
[1]: http://docs.oracle.com/javase/tutorial/essential/io/legacy.html
It appears you need to perform an operation running as Administrator. You can do this from Java using a command line
Process process = Runtime.getRuntime().exec(
"runas /user:" + localmachinename + "\administrator del " + filetodelete);
You need to read the output to see if it fails.
For me see http://technet.microsoft.com/en-us/library/cc771525.aspx
I have the following Java code which iterates through all the files in a directory and deletes them.
for(File file : tmpDir.listFiles())
{
file.delete();
}
It does however not delete all files. Some, usually 20-30, out of a couple of thousand, are left behind when I do this. Is it possible to fix this, or have I stumbled upon some Java voodoo that is best left alone?
It returns a boolean value, you should check that. From the JavaDoc:
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
You should check the value of the return and take action.
If it returns false it may well be that you do not have permission to delete the file.
In that case you can check whether the file is writeable by the application and if not attempt to make it writeable - again this returns a boolean. If successful you can try deleting again.
You could use a utility method:
private void deleteFile(final File f) throws IOException {
if (f.delete()) {
return;
}
if (!f.canWrite() && !f.setWritable(true)) {
throw new IOException("No write permissions on file '" + f + "' and cannot set writeable.");
}
if (!f.delete()) {
throw new IOException("Failed to delete file '" + f + "' even after setting writeable; file may be locked.");
}
}
I would also take their advice in the JavaDoc:
Note that the Files class defines the delete method to throw an
IOException when a file cannot be deleted. This is useful for error
reporting and to diagnose why a file cannot be deleted.
Provided that you are using Java 7 that is. That method throws a number of exceptions that you can handle:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Example taken from the Oracle tutorial page.
Forcing the garbage collector to run using System.gc(); made all the files deletable.
Make sure that you don't have any open stream like BufferedReader/Writer, FileReader/Writer etc. First close them, then you should be able to delete the file.
One more point, E.g. if you open a BufferedReader via another reader like FileReader, you must close both of the readers seperately.
So instead of this:
BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)););
do this:
BufferedReader bufferedReader = null;
FileReader fileReader = null;
try{
fileReader = new FileReader(readFile);
bufferedReader = new BufferedReader(fileReader);
}catch{...}
...
try {
fileReader.close();
bufferedReader .close();
readFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
I have an applicaton where I am processing 5000 files to 6000 files during a loop.
In a try and catch block I am reading the excel file and processing each individual cell.
Of course all the Files are in the same format, but In some files the data in the cell in may vary it may contain data or not
when ever there is an exception while processing 100th file,
the whole processing is stopped and exception is thrown,
But I dont want that scenario, instead if there is an exception at 100th file, the iteration should continue with 101th file.
And in the end I should know which file is processed succesfully and which one is failed.
Exception which I am gettng are
NumberFormatException and NullPointerExceptions
How to hand that scenario?
The basic idea is to put the try-catch block inside the loops.
for (File file : files) {
try {
parseExcelFile(file); // Do whatever you want to do with the file
}
catch (Exception e) {
logger.warn("Error occurs while parsing file : " + file, e);
}
}
The way I would do it is to create a Map using the filename as a key and in your loop for each exception you could store the exception under the filename. You'd know which exceptions you caught and the files they were associated with.
Map fileExceptions = new HashMap<String, Exception>();
for(File file : files){
try{
<file processing>
}
catch(NumberFormatException e){
fileExceptions.put(fileName, e);
}
catch(NullPointerException e){
fileExceptions.put(fileName, e);
}
}
It's hard to be more specific without seeing some code, but this could be a possible approach:
public void processFiles(List<File> fileList)
{
for (File thisFile : fileList) {
try {
processOneFile(thisFile);
}
catch (Exception ex) {
printLogMessage(thisFile.getName());
}
}
}
System.out.println("READ");
String currentWorldName = "RANDOM";
String propertiesFileDirectory = propertiesFolder + currentWorldName + "/props.properties";
String entitiesFolderDirectory = propertiesFolder + currentWorldName + "/Entities";
try
{
properties.load(new FileInputStream(propertiesFileDirectory));
}
catch (FileNotFoundException e)
{
//Since it doesn't exist either it was deleted by the user or hasn't been created yet.
createNewPropertiesFile();
}
catch (IOException e)
{
outputToLog("IOException when loading properties file for the world: '" + currentWorldName + "'.\n" + e.getStackTrace().toString());
}
//getting values from properties
//Now to read each properties file in Entities
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
//Read each file in the entities directory and load it into memory.
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
if (propertiesBelongsToEntityCH(entityPropertiesFileName))
{
//Get properties one way
}
else //The properties file we're working does not belong to CH.
{
//Get properties from the same file a different way
}
}
//This should never be hit since we have the file to read.
catch (FileNotFoundException e)
{
outputToLog("FileNotFoundException when loading entity properties file." + e.getMessage().toString());
}
//I don't know when/if this would be hit. It hasn't happened.
catch (IOException e)
{
outputToLog("IOException when loading entity properties file." + e.getMessage().toString());
}
catch (NullPointerException e)
{
entitiesFolder.mkdirs();
}
This HAS been working, I swear. It just started doing this.
Java keeps claiming that the "entitiesFolder" directory doesn't exist (I check with entitiesFolder.exists()). I have a solution for when that happens as you can see, because while my program is running it definitely can happen. Well it still claims that the folder doesn't exist, over and over.
I'm absolutely positive that it's the right directory because I print the "entitiesFolderDirectory" out to the console. It's correct. I can also be looking at the files inside of that folder and when mkdirs() runs it just deletes them all.
Java bug? This has completely broken my program.
I would write it without throwing a NullPointerException.
File entitiesFolder = new File(entitiesFolderDirectory);
entitiesFolder.mkdirs();
for (String entityPropertiesFileName : entitiesFolder.list()) {
//Do stuff
}
This will always work unless the folder could not be created.
What is the problem with this code? only one curly braces i found is missing else it is working fine.
This will create a dir test in c drive if does not exist else it will list the files in test dir over n over again
String entitiesFolderDirectory = "C:\\test";
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
System.out.println(entityPropertiesFileName);
}
}catch (NullPointerException e)
{
System.out.println("creating new folder");
entitiesFolder.mkdirs();
}