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
Related
I'am trying to copy a file to a directory and then deleting it, but file.delete() keeps returning false
Here is my code:
for (File file : list) {
if (!file.isDirectory()) {
try {
FileUtils.copyFileToDirectory(file, path);
file.setWritable(true);
System.out.println(file.delete());
if(file.exists()){
file.deleteOnExit();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
Few ideas that you can work it out.
If you want to delete file first close all the connections and streams. after that delete the file
Make sure you have the delete permissions for the file
Make sure you are in right directory. Try using absolute path for deleting the file, in case delete is not working. Path might not be correct for the file.
Use Files.delete. The delete(Path) method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. You can catch the exception to determine why the delete failed as follows: See Oracle docs here
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);
}
My aim is to delete a file in some directory present in linux using a java program. I have the following line that does that:
java.lang.Runtime.getRuntime().exec("/bin/rm -f " + fileToDelete.getAbsolutePath());
But I read that using linux commands from java program would be a costlier operation. Could anyone let me know if there is another way of doing this?
How about File#delete()
boolean isFileDeleted = fileToDelete.delete();
You could use a File object, as such:
// initializes your file with your full path (or use your "fileToDelete" variable)
File file = new File("myFile");
// attempts to set the file writable and returns boolean result
System.out.println("Could set file writable: " + file.setWritable(true));
// attempts to delete the file and returns boolean result
System.out.println("Deleted succesfullly: " + file.delete());
Permission / delete operations may throw an unchecked SecurityException.
if(file.exists())
boolean isSuccessful = file.delete();
Try this, it works in my Linux
File f= new File("Path");
try {
java.lang.Runtime.getRuntime().exec("rm -f " + f.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
I am trying to run this code which fails with the note:
gzip: /home/idob/workspace/DimesScheduler/*.gz: No such file or directory
The code:
ProcessBuilder gunzipPB = new ProcessBuilder("gunzip", System.getProperty("user.dir") + File.separator + "*");
gunzipPB.inheritIO();
int gunzipProcessExitValue;
try {
gunzipProcessExitValue = gunzipPB.start().waitFor();
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Service " + this.getClass().getSimpleName() + " could not finish creating WHOIS AS Prefix Table", e);
}
logger.info("Finished unzipping radb and ripe files. Process exit value : {}", gunzipProcessExitValue);
Exit value is 1.
Same command in terminal works just fine (the files exist).
What can be the problem?
Thanks.
Ido
EDIT:
After trying to use DirectoryStrem I am getting this exception:
java.nio.file.NoSuchFileException: /home/idob/workspace/DimesScheduler/*.gz
Any idea what can be the problem? The files do exist.
The full code:
ProcessBuilder radbDownloadPB = new ProcessBuilder("wget", "-q", "ftp://ftp.radb.net /radb/dbase/*.db.gz");
ProcessBuilder ripeDownloadPB = new ProcessBuilder("wget", "-q", "ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.route.gz");
radbDownloadPB.inheritIO();
ripeDownloadPB.inheritIO();
try {
int radbProcessExitValue = radbDownloadPB.start().waitFor();
logger.info("Finished downloading radb DB files. Process exit value : {}", radbProcessExitValue);
int ripeProcessExitValue = ripeDownloadPB.start().waitFor();
logger.info("Finished downloading ripe DB file. Process exit value : {}", ripeProcessExitValue);
// Unzipping the db files - need to process each file separately since java can't do the globing of '*'
try (DirectoryStream<Path> zippedFilesStream = Files.newDirectoryStream(Paths.get(System.getProperty("user.dir"), "*.gz"))){
for (Path zippedFilePath : zippedFilesStream) {
ProcessBuilder gunzipPB = new ProcessBuilder("gunzip", zippedFilePath.toString());
gunzipPB.inheritIO();
int gunzipProcessExitValue = gunzipPB.start().waitFor();
logger.debug("Finished unzipping file {}. Process exit value : {}", zippedFilePath, gunzipProcessExitValue);
}
}
logger.info("Finished unzipping ripe and radb DB file");
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Service " + this.getClass().getSimpleName() + " could not finish creating WHOIS AS Prefix Table", e);
}
Thanks...
the *.gz glob is not handled by the gunzip command, but the shell. For example, the shell will translate gunzip *.gz to gunzip a.gz b.gz. Now when you exec through java, you either have to invoke bash to do the globbing for you, or expand the glob in java, since gzip doesn't know how to handle the glob.
Java 7 has new libraries which make expanding glob patterns easier.
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.
i want to create a hardlink from a file "C:\xxx.log" to "C:\mklink\xxx.log" .
In cmd it works of course, but i want to write a software for this usecase.
So have to locate the existing file
Then make a hardlink
Then delete the old file
I started to implement but, i just know how to create a file. On google i found nothing about mklink \H for Java.
public void createFile() {
boolean flag = false;
// create File object
File stockFile = new File("c://mklink/test.txt");
try {
flag = stockFile.createNewFile();
} catch (IOException ioe) {
System.out.println("Error while Creating File in Java" + ioe);
}
System.out.println("stock file" + stockFile.getPath() + " created ");
}
There are 3 ways to create a hard link in JAVA.
JAVA 1.7 Supports hardlinks.
http://docs.oracle.com/javase/tutorial/essential/io/links.html#hardLink
JNA, The JNA allows you to make native system calls.
https://github.com/twall/jna
JNI, you could use C++ to create a hardlink and then call it through JAVA.
Hope this helps.
Link (soft or hard) is a OS feature that is not exposed to standard java API. I'd suggest you to run command mklink /h from java using Runitme.exec() or ProcessBuilder.
Or alternatively try to find 3rd party API that wraps this. Also check what's new in Java 7. Unfortunately I am not familiar with it but I know that they added rich file system API.
For posterity, I use the following method to create links on *nix/OSX or Windows. On windows mklink /j creates a "junction" which seems to be similar to a symlink.
protected void makeLink(File existingFile, File linkFile) throws IOException {
Process process;
String unixLnPath = "/bin/ln";
if (new File(unixLnPath).canExecute()) {
process =
Runtime.getRuntime().exec(
new String[] { unixLnPath, "-s", existingFile.getPath(), linkFile.getPath() });
} else {
process =
Runtime.getRuntime().exec(
new String[] { "cmd", "/c", "mklink", "/j", linkFile.getPath(), existingFile.getPath() });
}
int errorCode;
try {
errorCode = process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Link operation was interrupted", e);
}
if (errorCode != 0) {
logAndThrow("Could not create symlink from " + linkFile + " to " + existingFile, null);
}
}