So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.
Related
This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}
My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();
Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.
First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:
I've found a bunch of similiar questions there, but all the proposed solutions already exist in my code, so...
I have the following routine being called from different places in my app:
static private void writeToFile(String data) {
File file = new File("sdcard/output.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw = null;
try {
FileWriter fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
bw.append(new Date().toString() + " " + data);
bw.newLine();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(bw != null) {
bw.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Sometimes after a while strings stop to be added to a file. I've presumed it's something about syncronization - but once I've succeeded to catch it in debug mode and stepped all over the routine - every statement is executed without any exceptions.
Can you, please, tell what's wrong with my code?
I'm trying to close a RandomAccessFile but resource remain busy.
Code:
public boolean isOpen(RandomAccessFile f) {
try {
f.length() ;
return true ;
}
catch (IOException e) {
return false ;
}
}
this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");
Log is not showed and thread goes in loop.
When I try to access to my resource from shell it gives me "Device or Resource busy".
The only way to access is kill java process.
When you are trying to access the RandomAccessFile length(), method, it is already closed and thus you cannot access it anymore.
You probably want to use the length() method of File. Your loop cannot work as the RandomAccessFile was already closed.
But I must admit I am clueless on the low level reason why rfmRandomAccessFile would not really be closed. It could be a side effect of your strange loop trying to get the size of a closed file.
[edit:]Could not reproduce your issue with the following piece of code:
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("foobar.txt");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rws");
randomAccessFile.write(new byte[]{'f'});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(randomAccessFile !=null){
try {
randomAccessFile.close();
} catch (IOException e) {
//doh!
}
}
}
FileReader reader = null;
try {
reader = new FileReader(file);
char read = (char) reader.read();
System.out.println("what was written: "+read);
System.out.println("file size: "+file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){
try {
reader.close();
} catch (IOException e) {
//doh!
}
}
}
}
}
I am using Jackcess API in my Eclipse plugin project. I added jackcess-2.1.0.jar file under resources/lib. I included the jar under my Binary build and in build.properties. I successfully make a connection using connection string but my DatabaseBuilder.open() call is not executing. My code is
public void run() {
try {
File tempTarget = File.createTempFile("eap-mirror", "eap");
try {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
try {
FileUtils.copyFile(new File(templateFileString), tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
// Changes
try {
this.target = DatabaseBuilder.open(tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
Collection<String> tables = selectTables(source);
long time = System.currentTimeMillis();
for (String tableName : tables) {
long tTime = System.currentTimeMillis();
Table table = target.getTable(tableName);
System.out.print("Mirroring table " + tableName + "...");
table.setOverrideAutonumber(true);
copyTable(table, source, target);
System.out.println(" took "+ (System.currentTimeMillis() - tTime));
}
System.out.println("Done. Overall time: "+ (System.currentTimeMillis() - time));
System.out.println("done");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// More Code here
} catch (IOException e1) {
}
}
When I run the class in debug mode and I reach DatabaseBuilder.open call it fails.
Here is my project structure:
Can anyone tell me the possible reason for it ?
The .open method of DatabaseBuilder expects to open an existing well-formed Access database file. The .createTempFile method of java.io.File creates a 0-byte file. So, the code
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", "eap");
try (Database db = DatabaseBuilder.open(dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
will cause Jackcess to throw
java.io.IOException: Empty database file
when it tries to do DatabaseBuilder.open(dbFile).
Instead, you should DatabaseBuilder.create to convert the 0-byte file into a real Access database file like this
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", ".accdb");
dbFile.deleteOnExit();
try (Database db = DatabaseBuilder.create(Database.FileFormat.V2010, dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
The application I am working on has a terribly slow loading web page. If I run the following code it works fine but only because of the call to sleep. If I don't sleep then the InputStream is just a bunch of spaces, probably due to the application it is calling from. Is there any non-hack way around this?
public class PublishTool extends Thread {
private URL publishUrl;
private String filerLocation;
public PublishTool() {
}
public PublishTool(String publishUrl, String filerLocation) throws NibException {
try {
this.publishUrl = new URL(publishUrl);
} catch (MalformedURLException e) {
throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
}
this.filerLocation = filerLocation;
}
public void run() {
File filerFile = new File(filerLocation);
BufferedWriter writer = null;
try {
URLConnection conn = publishUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
writer = new BufferedWriter(new FileWriter(filerLocation));
Thread.sleep(1000l);
while (reader.ready()) {
writer.write(reader.readLine() + "\n");
}
} catch (MalformedURLException e) {
throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
} catch (IOException e) {
throw new IllegalStateException("IO Exception for : " + publishUrl + " " + filerLocation, e);
} catch (InterruptedException e) {
throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
} catch (NibException e) {
throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't use reader.ready(). Just call readLine() and let readLine() block until the data's ready. The end of the data will generally be signalled with a null line.
In case its helpful, a couple of code examples on my web site: reading from a URL.
Firstly, it would be helpful if you posted your actual code.
My guess the problem is calling Reader.ready. Similar to InputStream.available, that returns true if there is already buffered input. If it needs to wait for, say, a socket the it will return false. Generally you don't need ready. Use readLine, and break out of the loop if it returns null (for end of stream).