Reading Excel file safely using Apache POI [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Check if file is already open
I am making a swing utility in which i am creating and using a excel sheet by Apache poi.
If the file is already opened while i m trying to access it it throws an exception like some other process is using this excel file. So all i want is to check if that excel file is already opened and if yes then close it.

Did you do some Google search on this topic: Here is some I came up with
Java: Check if file is already open
check if a file is already open before trying to delete it
checking that an excel file is already opened by another application
I am copying the answer from the first question on stackoverflow here:
File file = new File(fileName);
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
} catch (OverlappingFileLockException e) {
// File is open by someone else
} finally {
lock.release();
}
Hope this will be of help.

Have you tried this:
File file = new File(pathToFile);
if (file.canRead()) {
<do whatever you are doing with the file>
}

Related

Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate]

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

Java: Can't read Tiff image file [duplicate]

This question already has answers here:
Can't read and write a TIFF image file using Java ImageIO standard library
(5 answers)
Closed 5 years ago.
I'm trying to read an image from a relative path:
String fp = "../resources/img/wc/text/039.tiff";
The following code succeeds:
File fi = new File(getClass().getResource(fp).getPath());
System.out.println("fi: " + fi);
if (fi.exists() && !fi.isDirectory()) {
System.out.println("file exists"); // <-- console prints this
}
try {
img = ImageIO.read(getClass().getResource(fp));
System.out.println("file read"); // <-- console prints this
} catch (IOException e) {
e.printStackTrace();
}
... but the following code just after it:
System.out.println(img.getType());
... fails, reporting:
Exception in thread "main" java.lang.NullPointerException
at com.ddc.fmwscanner.java.LoadImageApp.ddNextImage(LoadImageApp.java:60)
at com.ddc.fmwscanner.java.LoadImageApp.<init>(LoadImageApp.java:85)
at com.ddc.fmwscanner.main.FmwScanner.main(FmwScanner.java:15)
I know the image is valid, because I can open it using non-Java methods. However, those methods will not open the image from a .jar, so I need to use a pure Java method.
Any insight is appreciated.
This ended up being a problem with loading .tiff files in pure Java. Installing TwelveMonkeys ImageIO plugin did the trick. Thanks again, especially to #IlarioPierbattista, who directed me to the solution!

How to add a URL to download a file in java [duplicate]

This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 4 years ago.
I want to add a URL into my java program: http://www.markit.com/news/InterestRates_JPY_20160426.zip; so basically when you open this link a zip file is downloaded. How do I do that?
And then, I want to unzip the downloaded file in the java program as well.
How do I do these in java?
You can use zip4j to unzip your file.
To download a file in Java you can use this code.
try
{
String url = "download url";
String path = "C:/Users/...."; // Path to where the files is going to be downloaded.
ReadableByteChannel in = Channels.newChannel( new URL(url).openStream() );
FileOutputStream fileOutputStream = new FileOutputStream(path);
FileChannel out = fileOutputStream.getChannel();
out.transferFrom(in, 0, Long.MAX_VALUE);
}
catch (Exception e)
{
e.printStackTrace();
}

How can I open a file and notify when it is closed in Java?

My question is clear I think, is it possible to open a file automatically according to its extension then when it's closed get notify?
I try to open file with this way:
File f = new File(url);
Desktop.getDesktop().open(f);
But I can't get notification when the file closed, is there any alternative for that?
You can try to look at WatchService API
The WatchService API is designed for applications that need to be
notified about file change events.
You can also check if your file is closed or not like this using Apache:
boolean open = false;
try
{
org.apache.commons.io.FileUtils.touch(myFile);
open = true;
}
catch
{
open = false;
}
if(open == false){
// Show notification message.
}

Writing to text file, file not updating [duplicate]

This question already has answers here:
Writing String to Text File
(6 answers)
Closed 8 years ago.
I have been having some trouble: my previous question here explains it all. I was trying to write to a file in the external storage which on my device is /data/media or /sdcard. The file (when you adb pull it with device on) one saves two lines of text and then gets overwritten but once you adb pull it again in recovery with /data mounted, all the logs appear.
I have tried mounting /data and then writing to the file but still no luck... Any help?
You code does not flush the BufferedWriter, so data are not written to log file but stays in the buffer.
How about replace code in try block of method 'writeToLog' of your code by following code?
BufferedWriter bw = new BufferedWriter(new FileWriter(logFile, true))
PrintWriter out = new PrintWriter(bw);
out.println(text);
bw.flush() // Explicitly flushbufferedWriter
out.close();

Categories

Resources