I need to know what is the best way to export excel file into my .jar code.
I used GetDesktop open file statement, and that works good when I run it inside of Eclipse IDE. But when I export my code into a .JAR, the excel sheet will not open, it will not do anything.
public void actionPerformed(ActionEvent e) {
try { Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
desktop.open(new File("Resources/pics/chart 2.xls"));
} catch (IOException ioe) {
ioe.printStackTrace();
}}
I have a picture image in a jframe, and I have 2 buttons, inside of the picture, for the user to click on. Depends on which button they click on, I need that certain excel file to open. Just for viewing purposes, no editing is involved. I tried using apache POI, but the excel file did not open at all, but when I use the code above at least it opens in eclipse. I see that there is others with the same problem, but mine I need it to just open excel not edit.
thanks
You must copy it out of the jar. You can get an inputstream using InputStream in = ClassYouAreIn.class.getResource("someFile.xls"). Here is an example:
try (InputStream in = ClassYouAreIn.class.getResource("someFile.xls")) {
// copy it here, for example using:
Files.copy(in, Paths.get("somefile.xls"), StandardCopyOption.REPLACE_EXISTING);
}
NB: Your catch code is really bad: exceptions contain 4 interesting bits of information (type, message, stacktrace, causal chain) and you're chucking 3 of the 4 things, AND you are causing a cascade of errors by not aborting. You should always just throw them onwards (put throws IOException on this method) unless you have an ACTUAL strategy to deal with it (and logging / printing it is not dealing with it!).
Related
I basically want to make a watch service (or something like it) that checks if a file has been closed and instantly remove that file if it did close(finished executing).
How I can achieve this? please give me a cmd commands or some code(i prefer Java).
Ok, this should not be hard to do, if you google a bit you find a Java-File Method called file.canWrite() which basically returns if a file is locked by an other program or so.
So codewise what you could do is something like this.
boolean isDeleted = false;
File f = new File (// Put your file here);
while (!isDeleted) {
if (f.canWrite()) {
f.delete();
isDeleted = true;
} else {
try {
Thread.sleep(10); // Throws Exception you need to catch somewhere...
} catch (Exception e) {}
}
}
This code you need to include into some Java-Program. I added a simple Thread.sleep(10) that your PC does not have to check aaaaaalllllllll the time.
See Check if a file is locked in Java
Other possibility would be trying to rename the file with file.renameTo("some_path.txt"); as this method also returns a boolean whether it was successfull! Just note that you then need to update the file again before removing it.
Last possibility I see is pretty similar to the second one. You try to delete the file by calling file.delete(); If the file still exists you know it was not successful and loop because of that.
I assume you mean when the file is not open in another program, and you cannot make changes to that other program? (If you are talking about your own program opening the file, this is much easier.)
On Windows, it is not very easy to tell which program has a file open. Take a look at https://superuser.com/questions/117902/find-out-which-process-is-locking-a-file-or-folder-in-windows for some options. I like the handle tool for this, but it has to run as Administrator, which may be a problem. You can try renaming or writing to the file, as suggested at Check if a file is locked in Java
Once you have a script that determines whether the file is open to your satisfaction, it should be fairly straightforward to write a script which loops while testing if the file is open and then deletes file.
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the 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
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
I am having a situation where i receive a ms-word (docx) document as a stream/bytearray from a webservice.
I then try to recreate the file, giving it the same name and content as before.
If i compare the original file and the one created after the download, then they are identical.
However, when i try to open the new one in word i get an error, and if accept the riscs i can open it.
If i look at the properties af the file in windows, the new one is missing a lot of information.
Any one know how to recreate the properties so the file can be opened without errors?
Just an extra piece of information.. If i use .doc (word97-2003) documents all is working fine, only .docx documents are a problem (also .xlsx and all the office 2007-2010 documents).
This is my code creating the files..
private static void saveBytesAsFile(String path, String filename, byte[] data){
try {
File dir = new File(path);
dir.mkdirs();
OutputStream os = new FileOutputStream(path + "/" + filename);
os.write(data);
os.flush();
os.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I compared the original and the recreated file in notepad++, and got the result that they are identical.
This is how i see that some properties are missing.
Image of properties
These are the warnings i get from word:
If i press ok on the first and yes on the second i can open the document anyway.
Word Warnings
If you are asked to "accept the risks" then this sounds more like the default Word behaviour when downloading documents from the internet, not an error. You can change the Word behaviour from the Word Options, Trust Center (assuming you are using Word 2007 or later).
So I doubt that the missing properties are an issue. It is possible to change the creation date of the document that you are re-creating, by changing the system clock before building your new document (based on the previous document's content). I am not recommending these steps.
SOLUTION
It turned out that there were no problem with the properties.
It was simply so that somewhere in the services that provided the document data an extra blank character was added at the end of the file data.
This resulted in a mismatch of the expected file length and the actual one, and therefore the office components complained when trying to open the documents.
And this also prevented the properties of the file to be parsed.
What was pretty annoying, was that file comparison tools did not catch this. (Or maybe there need to be some configuration of trailing spaces not beeing ignored.)
I am attempting to write a JApplet that uses information in a text file to load and save data from. I have successfully got the applet to load the information, but the saving appears to be having issues. I have included the code to save below. the file name I am using is the same as I use to write to. The file must be included in the JAR when I run because the applet initializes properly. Is there any reason why the writing sin't working properly? i have resorted to calling this method from both the stop() and destroy() methods.
As a note, the load and saving both work perfectly when run from eclipse, but when in a JAR only the loading works, but nothing saves so I can't change the load data.
Ideally, I want this saveLocations() method to be called whenever the page is closed or refreshed.
NOTE: mOUtputStream is indeed a PrintWriter (it used to be an OutputStream, I guess I should change the name)
Thanks so much in advance for the help.
private void saveLocations() throws IOException {
//JOptionPane.showMessageDialog(null, "Alert", "Saving", JOptionPane.INFORMATION_MESSAGE);
// System.out.println("saving!");
try {
mOutputStream = new PrintWriter(new File(getClass().getResource("/listings/saveData.txt").toURI()));
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(locations.size());
for (Location l : locations) {
System.out.println("r: " + l.getRawListing());
mOutputStream.print(l.getRawListing()+ "\n");
}
if (mOutputStream != null)
mOutputStream.close();
}
You can't write to a file inside a JAR file -- period. Don't even try. If you need to write to a file, then that file has to be outside the JAR. For an applet, that would require it to be signed, and to ask the user for specific permission to do so.
In the applet case, I'm not sure what copy of the JAR file you're hoping will be written to: the copy in the browser cache, or the copy on the server? Either way, it's not going to happen.
FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");
Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.
Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:
File file = new File("member.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("test");
} catch (IOException e) {
e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
Closing is mandatory since it flushes the written data into the file and releases the file lock.
Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.
If the file is successfully created (no exception is raised), it is in the current working directory.
For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."
In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.
In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.
It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.
If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).
You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.