This question already has answers here:
Check if a file is open before reading it?
(2 answers)
Closed 9 years ago.
How to check if a file / folder is open before i try to delete it.
Am deleting it programmatically.. before deleting, need to check whether its opened or not
I want something like this,
if(file/folder is open){
//do not delete it
}else{
//delete it
}
I tried the below set of two codes, but nothing is working
File scrptFile=new File(dirFile);
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(scrptFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
System.out.println("file is not locked");
} else {
// Do stuff you need to do with a file that IS locked
System.out.println("file is locked");
}
File file = new File(dirFile);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
// Ok. You get the lock
System.out.println("Ok. You get the lock");
} catch (OverlappingFileLockException e) {
// File is open by someone else
System.out.println("File is open by someone else");
} finally {
lock.release();
}
You can make use of Apache commons io api,
boolean flagFileNotInUse = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
flagFileNotInUse = true;
} catch (IOException e) {
flagFileNotInUse = false;
}
// Then check value of flagFileNotInUse ,
flagFileNotInUse = true, means file not in use
flagFileNotInUse = false, means file in use
Related
I'm having a problem with an assignment from school. I'm meant to output an arraylist of objects to a file, which I can do. But I'm supposed to check if the file exists, and if it does, then to output to that file, and not create a new one.
I've tried putting the FileOutputStream declaration outside of my if statement, but then the file will always exist.
I've also tried creating a new ObjectOutputStream in my first half of the if statement, but I get an IOException about the headers.
How do I write the objects (of class Employee) to a file that already exists?
public void saveEmployeesToFile() {
try {
File employeeFile = new File("CurrentEmployees.emp");
if (employeeFile.exists()) {
System.out.println("File already exists");
} else {
FileOutputStream employeeFileObject = new FileOutputStream(employeeFile);
ObjectOutputStream output = new ObjectOutputStream(employeeFileObject);
for (Employee thisEmp : getEmployees()) {
output.writeObject(thisEmp);
}
System.out.println("Employees successfully saved to new file");
employeeFileObject.close();
output.close();
}
} catch (IOException ioe) {
System.out.println("Error initializing stream");
System.out.println(ioe.getMessage());
}
}
You can leverage the newer NIO package.
Your question is essentially, "how do I create a FileOuputStream for a file that already exists?"
Path employeeFilePath = Paths.get(employeeFile.toURI());
FileOutputStream employeeFileObject;
if (employeeFile.exists()) {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.TRUNCATE_EXISTING);
}
else {
employeeFileObject = Files.newOutputStream(employeeFilePath, StandardOpenOption.CREATE_NEW);
}
// Proceed to write data
I try to check file is opened or not in java using following examples . I use 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
}
This brings me a wrong formation . When I am not opened the exact file, this show me the file has opened. If file is not opened, result is false and this cannot be possible .
Other example is here,
public boolean isFileOpened(File file){
boolean res = false;
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
FileLock lock = channel.lock();
try {
//The file is not already opened
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is open by someone else
res = true;
} finally {
lock.release();
}
return res;
}
This also brings me incorrect information.
I get these examples from here Java: Check if file is already open
Now my problem is how could I check file is opened or not in java correctly ?
Thank you.
I'm using Java in a really big application and some time i have to use temp file. Those file i want to be deleted at the application close, this is a simple snapshot i'm using:
File tempFile = File.createTempFile("sign_", "tmp.pdf");
tempFile.deleteOnExit();
I'm not reporting all the code since is really big and i have many class working each other. I would know which could be the reason that avoid the delete on closure of certain file (some file are deleted other not, but they came always from the same piece of code the one that are not deleted).
Edit: i have already read this example but i think i need some "theoric" motivation and not code example to find the reason.
The method "deleteOnExit()" only works if the VM terminates normally. If the VM crash or forced termination the file might remain undeleted.
I don't know how it is implemented, but you could try to put the tempFile.deleteOnExit() inside the finally.
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
tempFile.deleteOnExit();
tempFile = null;
//Added a call to suggest the Garbage Collector
//To collect the reference and remove
System.gc();
}
}
Or maybe, close all the references to the file and then call "File.delete()" to delete immediate.
If anyone is working, problably some reference to the file exists. In this way, you can try to force the file to be deleted using the org.apache.commons.io.FileUtils.
Example org.apache.commons.io.FileUtils:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileUtils.forceDelete(tempFile);
System.out.println("File deleted");
}
}
Example org.apache.commons.io.FileDeleteStrategy:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileDeleteStrategy.FORCE.delete(tempFile);
System.out.println("File deleted");
}
}
I've been trying to create files inside some directories but haven't been able to figure it out.
The point is to create text files inside package dir: com.resources.files but my idea doesn't work.
public boolean archiveFile() {
//
InputStream str = this.getClass().getResourceAsStream("/com/resources/files/"+Filename.txt
boolean bol = false;
file = new File( str.toString() );
if(!file.exists()) {
try {
file.createNewFile();
bol = true;
} catch (Exception e) {
e.printStackTrace();
}// try-catch
}else {
bol = false;
} // if - else
return bol;
}// archiveFile
Resources are not files, and resource paths are not directories. Consider the case where a WAR file is being executed without unzipping.
You can't do this.
I'm trying to make each thread read its own text file.
private void burden() {
File mainFolder = new File("C:\\FilesToRead");
File[] files = mainFolder.listFiles();
String freeFile;
for (File file : files) {
FileChannel channel;
FileLock lock = null;
try {
channel = new RandomAccessFile(file, "r").getChannel();;
lock = channel.lock();
// Ok. We get the lock
readFile(file.getName());
} catch (OverlappingFileLockException e) {
continue; // File is open by someone else
} catch (FileNotFoundException f) {
} catch (IOException ex) {
} catch (NonWritableChannelException n) {
System.out.println("NonWritableChannelException");
} finally {
try {
lock.release();
} catch (IOException ex) {
System.out.println("IOException!");
}
}
}
} // burden();
I get this picture in the debugger:
The next step will bring me to the NonWritableChannelException.
I can't understand why as I tried to lock file for reading.
The javadoc gives the answer. You use .lock(), which is equivalent to calling .lock(0L, Long.MAX_VALUE, false).
And the third parameter, a boolean, is described as (emphasis mine):
true to request a shared lock, in which case this channel must be open for reading (and possibly writing); false to request an exclusive lock, in which case this channel must be open for writing (and possibly reading)
You have to .lock(0L, Long.MAX_VALUE, true)
Also, if you are using Java 7, use FileChannel.open()
you also need to lock the writable channel here so make your code,
channel = new RandomAccessFile(file, "rw").getChannel();
This should work.