Java Forum / General / August 2007
Is It Possible to Make Java Find a File on Your Computer?
julielaurek@gmail.com - 13 Aug 2007 22:38 GMT Hi everyone!
So I was using Runtime.getRuntime().exec("my excel location") to launch Excel on my PC. However, my excel is found in a folder called OFFICE11 instead of OFFICE, as per someone else's example I stumbled on online. But the application I'm creating will have to be able to access the user's excel program whatever the name of the folder it is located in. Is there a way to make your Java application search your computer until it hits excel.exe, then use that excel file location for the rest of a program?
Thanks!
JL
Manish Pandit - 13 Aug 2007 22:52 GMT On Aug 13, 2:38 pm, "julielau...@gmail.com" <julielau...@gmail.com> wrote:
> Hi everyone! > [quoted text clipped - 10 lines] > > JL Consider using configuration/properties file and have your code read it. Something like:
excel.executable=c:\\winnt\\microsoft\\excel.exe
Alternatively you can have a comma separated list of possible locations and have your code check every one of them. If all configured locations fail, have the user browse to the location and double click the file himself, as it is possible that he may not have excel installed on his box (I dont!).
-cheers, Manish
Andrew Thompson - 13 Aug 2007 23:42 GMT >On Aug 13, 2:38 pm, "julielau...@gmail.com" <julielau...@gmail.com> >wrote: >> Hi everyone! 'search disk for Excel'
>Consider using configuration/properties file and have your code read >it. Something like: [quoted text clipped - 5 lines] >configured locations fail, have the user browse to the location and >double click the file himself, ... And/Or offer a 'search' facility to the end user.
See File.list() and File.listFiles() (as well as variants that accept FileFilter's). Those methods combined wih File.isDirectory() in a recursive loop applied to any volume, should be able to list and check every file on the given volume.
>...as it is possible that he may not have >excel installed on his box (I dont!). I use OpenOffice (neither do I).
 Signature Andrew Thompson http://www.athompson.info/andrew/
Knute Johnson - 13 Aug 2007 23:50 GMT > Hi everyone! > [quoted text clipped - 10 lines] > > JL They added some really nice features to version 6. The Desktop class being one of my favorites. Runtime.exec() has a bunch of issues. I haven't tested this on any version of Linux but on XP it works great.
import java.awt.*; import java.io.*;
public class test6 { public static void main(String[] args) throws Exception { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.OPEN)) { desktop.open(new File("path_to_.xls")); } } else System.out.println("Desktop not supported"); } }
 Signature Knute Johnson email s/nospam/knute/
Jeff Higgins - 14 Aug 2007 15:09 GMT > They added some really nice features to version 6. The Desktop class > being one of my favorites. Runtime.exec() has a bunch of issues. I > haven't tested this on any version of Linux but on XP it works great. Not having been aware of the Desktop class, Knutes' post interested me enough to attempt to run his example. Several days ago I installed the most recent version of Eclipse (Europa or 3.3). Now I am suprised when I create a new file "path_to_.xls" in my project folder and an instance of MS Excel is opened in a new Eclipse editor window! I don't know if this capability was present in 3.2, but it sure is in 3.3. Kinda neat. JH
Lew - 14 Aug 2007 22:39 GMT >> They added some really nice features to version 6. The Desktop class >> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 6 lines] > instance of MS Excel is opened in a new Eclipse editor window! > I don't know if this capability was present in 3.2, but it sure is in 3.3. Would this work to bring up Open Office if I don't have Excel on my machine?
 Signature Lew
julielaurek@gmail.com - 14 Aug 2007 23:14 GMT > >> They added some really nice features to version 6. The Desktop class > >> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 11 lines] > -- > Lew Ok. To summarize the long story that is about to follow, thanks to Real's code I did succeed in getting to excel without manually specifying the folder in which EXCEL.EXE was located so Thanks!!!!!!
Now the longer version: I have actually been trying options 2 to 4 all day. Still need to get down to 1 and 5, which I had thought would take more time. Jeff and Knute, I tried the path_to_.xls... it hates me and it's not working.:) I was using Eclipse 3.2 so I upgraded to Europa and still ... nothing. would any of you happen to know why it won't work? The error I get is:
Exception in thread "main" java.lang.IllegalArgumentException: The file: path_to_.xls doesn't exist. at java.awt.Desktop.checkFileValidation(Unknown Source) at java.awt.Desktop.open(Unknown Source) at SpreadSheetTester.main(SpreadSheetTester.java:131)
I had assumed Java would recognize path_to_.xls just like it would user.dir, for example?
Andrew; still recursing though the files. For now this method: http://docs.google.com/Doc?id=dcqbcf4x_31fmcc4s
should work if I use it this way: myRecursor(new File ("C:\\Program Files\\Microsoft Office\ \OFFICE11") ,"EXCEL.EXE");
Basically, I should be able to see "Excel.exe - Sorry for the endless number of System.out.printlns. Debugging. :) ) but it gives me a long list of "Test1"s which means that it actually never does see EXCEL.EXE? However, when I wrote another method to view all the contents of "C:\\Program Files\\Microsoft Office\\OFFICE11" as a list, it does show EXCEL.EXE. -in bold here, if anyone would like to double- check or cross-check for possible errors : http://docs.google.com/Doc?id=dcqbcf4x_32hps8pz )
Real; Thanks again! the second piece of code couldn't recognize any of my paths, though: where you had /path/sheet.xls , I put the following. C:\\Documents and Settings\\SpencerLAB\\pageWatchSpreadSheet.xls helpFile.toString(), basically File helpFile = new File( (new File (System.getProperty(dir)).getCanonicalPath(), "pageWatchSpreadSheet.xls) (can't remember why I had to go through new File twice but there was some error when I didn't, before today's problems. For some reason I always get some error that says System can't recognize C:\Documents or anything I typed in, so I haven't been able to open the excel sheet I created in my class. But I'm still debugging.
I haven't used Calc yet. Is it's exec file also Calc.exe, CALC.EXE... I will be dealing with OpenOffice right after I'm done with Excel. Are there any other popular Windows spreadsheet types/formats? I tried wiki-ing but I got a really long list and I wasn't sure what the top few most used ones were...
Thanks again for your suggestions, guys.
Cheers! JL
Knute Johnson - 15 Aug 2007 00:21 GMT >> Lew > [quoted text clipped - 18 lines] > I had assumed Java would recognize path_to_.xls just like it would > user.dir, for example? path_to_.xls is rhetorical. It is the path/filename of your xls file. It doesn't care where EXCEL.EXE is or whether you have MS Excel or Open Office. It is similar to typing the file name at a dos prompt or double clicking on the file icon in Explorer. It loads the appropriate program and file.
 Signature Knute Johnson email s/nospam/knute/
Jeff Higgins - 15 Aug 2007 16:07 GMT >>> They added some really nice features to version 6. The Desktop class >>> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 10 lines] > Would this work to bring up Open Office if I don't have Excel on my > machine? Um, Maybe? I've occasionally thought of trying out OpenOffice, thanks for the impetus. Right now I'm on a \home entertainment\ computer - my regular pc had to go to the shop :( - back soon :) This Platform = WinXP SP2, MS Word and Excel Version 7, Eclipse 3.3 Old processor, little memory, slow disk. Anyway, Word & Excel seem to work fine. Writer & Calc seem to have trouble displaying toolbars correctly. Probably just the old pc. Maybe this functionality isn't new. I seem to recall seeing Open with... | In-place Editor in 3.2, may be wrong, not sure. JH
julielaurek@gmail.com - 15 Aug 2007 21:39 GMT > >>> They added some really nice features to version 6. The Desktop class > >>> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 23 lines] > in 3.2, may be wrong, not sure. > JH Still working but just in case somebody needs it, this worked for the second piece of Real's code I couldn't run : String[] cmdArray = {"cmd", "/c", "start", "\"\"", helpFile.getAbsolutePath()}; Runtime.getRuntime().exec(cmdArray);
i.e: class StartExcel { public static void main(String args[]) throws java.io.IOException { // Win XP String[] cmdArray = {"cmd", "/c", "start", "\"\"", helpFile.getAbsolutePath()}; Runtime.getRuntime().exec(cmdArray); }
}
cheers!
JL
Jeff Higgins - 16 Aug 2007 00:52 GMT julielaurek wrote:
> Still working but just in case somebody needs it, this worked for the > second piece of Real's code I couldn't run : > String[] cmdArray = {"cmd", "/c", "start", "\"\"", > helpFile.getAbsolutePath()}; > Runtime.getRuntime().exec(cmdArray); I'm not sure where the helpFile part came in ? I must have missed something. Anyway, when I run Real's example with argument C:/Documents and Settings/Default User/path_to_.xls" I get the exception you expressed, but not when I run it with the DOS file path shown below.
class StartExcel { public static void main(String args[]) throws java.io.IOException { // Win XP Runtime.getRuntime().exec("cmd /c start c:/docume~1/defaul~1/path_to.xls"); } }
My humble opinion: some variant of the suggestions offered by Manish or Andrew - just ask the user where to find the executable, either by dialog with a live user or config file.
Real Gagnon - 16 Aug 2007 03:39 GMT "Jeff Higgins" <oohiggins@yahoo.com> wrote in news:WkMwi.33$oa7.27 @newsfe12.lga:
> Anyway, when I run Real's example with argument > C:/Documents and Settings/Default User/path_to_.xls" [quoted text clipped - 10 lines] > } > } It's because when you have a space in the filename passed to the CMD start command you need to specified a "title". This is a "feature" of the start command! So something like
String[] cmdArray = {"cmd", "/c", "start", "\"\"", "\path\with\a space\sheet.xls"}; Runtime.getRuntime().exec(cmdArray);
should do the job. The fourth item of the cmdArray is the empty title.
Bye.
 Signature Real Gagnon from Quebec, Canada * Java, Javascript, VBScript and PowerBuilder code snippets * http://www.rgagnon.com/howto.html * http://www.rgagnon.com/bigindex.html
Jeff Higgins - 16 Aug 2007 13:23 GMT >> Anyway, when I run Real's example with argument >> C:/Documents and Settings/Default User/path_to_.xls" >> I get the exception you expressed, but >> not when I run it with the DOS file path shown below. [snip]
> It's because when you have a space in the filename passed to the CMD > start command you need to specified a "title". This is a "feature" of the [quoted text clipped - 5 lines] > > should do the job. The fourth item of the cmdArray is the empty title. Oops, Thanks Real. Good case for read the famous manual. Some links to the manual for future reference.
<http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/s tart.mspx> <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/n tcmds.mspx> <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/c md.mspx> <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/n tcmds_shelloverview.mspx>
Knute Johnson - 16 Aug 2007 04:13 GMT > julielaurek wrote: >> Still working but just in case somebody needs it, this worked for the [quoted text clipped - 22 lines] > by Manish or Andrew - just ask the user where to find the executable, > either by dialog with a live user or config file. You missed my point completely (you weren't the only one). The path_to_.xls is rhetorical. All you have to specify is the path to your object file. You don't need to know about what or where the program is that will manipulate it. It works if you have MS Excel or Open Office or whatever.
 Signature Knute Johnson email s/nospam/knute/
Jeff Higgins - 16 Aug 2007 12:06 GMT > You missed my point completely (you weren't the only one). The > path_to_.xls is rhetorical. No, I did not miss your point. I named my file "path_to_.xls" as given in your example.
Your excellent example worked for me exactly as advertised from the very first run.
I thank you for bringing this class to my attention.
I think B.L, Massengill's example down thread is also very nice.
All you have to specify is the path to your
> object file. You don't need to know about what or where the program is > that will manipulate it. It works if you have MS Excel or Open Office or > whatever. Andrew Thompson - 16 Aug 2007 02:31 GMT >>> They added some really nice features to version 6. The Desktop class >>> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 3 lines] > >Would this work to bring up Open Office if I don't have Excel on my machine? ..hmmm. Yes, no, maybe..
I was playing with this code..
<code> import java.awt.*; import java.io.*;
class FileTypeHelper {
public static boolean openFile(File document) throws Exception { Desktop dt = Desktop.getDesktop(); try { dt.open( document ); return true; } catch (UnsupportedOperationException ex) { return false; } }
public static void main(String[] args) { File f = new File("Site.xls"); try { System.out.println(openFile(f)); } catch(Exception ex) { ex.printStackTrace(); } } } </code>
..and can report the following.
This PC is running 1.6, Win XP Pro, no Excel but OpenOffice..
When that code runs, and "Site.xls" exists in the current directory, it will open the file in OpenOffice as an *editable* file, which confused me since there is also the method Desktop.edit(File), which is intended to open a file for edit (maybe OO has no concept of uneditable* files?). In any case, when I change the above to 'edit' - it fails and throws an 'Unsupported' exception.
* Beyond what is flagged on the file itself.
I was trying to include some data in my post, to turn the code above into an SSCCE (I could probably load a smallish XLS to my site if anybody else is interested in running their own tests to see the results) so tried created a CSV file and 'claiming' (by the file extension) that it was .XLS.
When I specified 'open' for that '.XLS', OpenOffice was invoked, but it dropped the content into the 'Writer' (text editor), rather than 'Calc' (spreadsheet).
After I'd changed the name to .csv, the method opened it in ..Notepad. :-(
Here is the text used in my simple (3 field, 3 line) CSV.. **************** "January",43.2,"Midge Green" "February",48.9,"John Smiley" "March",45.6,"Minh Truong" ****************
(As an aside - I would be looking to use the Desktop methods before going off to try and find anything, the strategy outlined by Manish and myself early in the thread should probably be considered an 'if all else fails' fall-back strategy. I am curious to check that the simple 'open' command will end in an *editable* file in *Excel*.)
 Signature Andrew Thompson http://www.athompson.info/andrew/
Knute Johnson - 16 Aug 2007 04:22 GMT >>>> They added some really nice features to version 6. The Desktop class >>>> being one of my favorites. Runtime.exec() has a bunch of issues. I [quoted text clipped - 78 lines] > the simple 'open' command will end in an *editable* > file in *Excel*.) Desktop.open() opens the file in the appropriate program eg. an .xls file will be opened with MS Excel if you have it installed or OO Calc if you have that installed. Whatever would happen if you typed the file name on the command line or double clicked on it in Explorer. Desktop.edit() opens it in the default editor.
Desktop is so simple to use everybody has been confused by my "path_to_.xls". That was supposed to mean "put the path to your .xls file here." I think it is far superior to using Runtime.exec() and more portable since with exec() you have to know what program is going to be run.
 Signature Knute Johnson email s/nospam/knute/
Lew - 16 Aug 2007 04:48 GMT > Desktop.open() opens the file in the appropriate program eg. an .xls > file will be opened with MS Excel if you have it installed or OO Calc if [quoted text clipped - 7 lines] > portable since with exec() you have to know what program is going to be > run. In other words, Desktop exploits the file association of the host OS, correct?
There used to be a lot of discussion about active data, that is, data files that execute themselves. Helper-app associations essentially achieve that, at least appear to, with the added flexibility of user choice about which app actually provides the behaviors for a given data class like spreadsheets.
The fact that Desktop respects local behavior associations makes it most potent indeed.
 Signature Lew
Knute Johnson - 16 Aug 2007 05:53 GMT >> Desktop.open() opens the file in the appropriate program eg. an .xls >> file will be opened with MS Excel if you have it installed or OO Calc [quoted text clipped - 10 lines] > In other words, Desktop exploits the file association of the host OS, > correct? Yes!
> There used to be a lot of discussion about active data, that is, data > files that execute themselves. Helper-app associations essentially > achieve that, at least appear to, with the added flexibility of user > choice about which app actually provides the behaviors for a given data > class like spreadsheets. Very OO!
> The fact that Desktop respects local behavior associations makes it most > potent indeed. At least you got my point Lew :-). I was using Runtime.exec() to display some user docs in one of my programs and having all kinds of problems with, and it took a lot of code. With Desktop it was so simple and the error handling if there is no appropriate program is just an exception.
 Signature Knute Johnson email s/nospam/knute/
Andrew Thompson - 16 Aug 2007 07:55 GMT (Lew)
>> The fact that Desktop respects local behavior associations makes it most >> potent indeed. > >At least you got my point Lew :-). (defensive) Hey! I *did* get your point, though I may not have expressed that extremely well. I'm confident Jeff H. did as well.
It seems much more sensible targeting the filetype than searching for an (any) .exe that you 'reckon' might be able to handle the file.
I thought the entire demo. with .xls and OpenOffice should have caught the OP's attention, but they (AFAIR) seem hell-bent on finding a file (.exe) that does not exist on ..my system, Manish's system..
( To be honest Knute, I noticed the mention of ".xls" in your code, took note of the method, entirely missed the "path" part that seemed to confuse others, and was off at the 1.6 JDocs already thinking of writing my own little example/test. Maybe the fact I was very drunk at the time, might explain why I wrote my own code, rather than actually trying yours.. ;)
 Signature Andrew Thompson http://www.athompson.info/andrew/
Knute Johnson - 16 Aug 2007 21:19 GMT > (Lew) >>> The fact that Desktop respects local behavior associations makes it most [quoted text clipped - 21 lines] > drunk at the time, might explain why I wrote my own > code, rather than actually trying yours.. ;) Hey I stand corrected. You and Jeff got what I was saying even when I didn't know :-).
 Signature Knute Johnson email s/nospam/knute/
blmblm@myrealbox.com - 16 Aug 2007 08:10 GMT > > Desktop.open() opens the file in the appropriate program eg. an .xls > > file will be opened with MS Excel if you have it installed or OO Calc if [quoted text clipped - 17 lines] > The fact that Desktop respects local behavior associations makes it most > potent indeed. I read this post and thought to myself "hm, this idea of file associations seems fairly standardized in the Windows world, but in Unix?" So I tried the almost-self-contained example upthread (in a post by Andrew Thompson) on a Linux box [*], and .... Wow. Nothing very useful happens in a text-only console, which is not a huge surprise, but under GNOME (desktop environment), opening "empty.doc" brings up OpenOffice Writer. Pretty cool, if one likes this sort of functionality!
[*] Fedora Core 4, if it matters.
Further investigation (skimming an entry in Sun's tutorial about the new Desktop class and the API) indicates that file associations are obtained via some sort of interaction with GNOME. Experiment indicates that the "open", "browse", and "mail" actions Just Work (to bring up appropriate programs), but that "edit" and "print" aren't supported. Huh. I'm mildly curious about -- well, several things:
Is the lack of support for editing and printing is true on all Linux (and Unix?) systems? If so, I wonder why.
What happens if you try this stuff under a window manager / desktop environment other than GNOME?
Is it easy to configure things to bring up one's own choice of "appropriate programs" rather than whatever is set up by default (on my system, Firefox for "browse", Evolution for "mail", and for "open" something based on the file's extension -- e.g., OO Writer for .doc, gedit for .txt)?
Below are two pieces of code, one to check which functions are supported and another to try the ones that are on my system (open, browse, mail), in case anyone wants to report results on other systems. Note that is pretty much quick-and-dirty-hack code.
==== check what's supported ====
import java.awt.*; import java.io.*;
public class DesktopCheck {
public static void main(String[] args) throws Exception { System.out.println("desktop supported? " + Desktop.isDesktopSupported()); Desktop dt = Desktop.getDesktop(); for (Desktop.Action a : Desktop.Action.values()) { System.out.println("action " + a + " supported? " + dt.isSupported(a)); } } }
==== try some Desktop actions (adapted from Andrew's example) ====
import java.awt.*; import java.io.*; import java.net.*;
public class FileAssociation {
public static void open(File document) throws Exception { Desktop dt = Desktop.getDesktop(); dt.open(document); } public static void browse(URI document) throws Exception { Desktop dt = Desktop.getDesktop(); dt.browse(document); } public static void mail(URI document) throws Exception { Desktop dt = Desktop.getDesktop(); dt.mail(document); }
public static void main(String[] args) { if (args.length < 3) { System.err.println("Need parameters: " + "filename to open, URL to browse, mail address"); System.exit(1); } try { open(new File(args[0])); } catch(Exception ex) { ex.printStackTrace(); } try { browse(new URI(args[1])); } catch(Exception ex) { ex.printStackTrace(); } try { mail(new URI("mailto:" + args[2])); } catch(Exception ex) { ex.printStackTrace(); } } }
 Signature B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor.
blmblm@myrealbox.com - 16 Aug 2007 07:39 GMT [ snip ]
> When I specified 'open' for that '.XLS', OpenOffice > was invoked, but it dropped the content into the > 'Writer' (text editor), rather than 'Calc' (spreadsheet). Nitpick: I'd call OO Writer a word processor rather than a text editor, since it seems more like MS Word than, say, Notepad. No?
[ snip ]
 Signature B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor.
Andrew Thompson - 16 Aug 2007 08:05 GMT >[ snip ] > [quoted text clipped - 4 lines] >Nitpick: I'd call OO Writer a word processor rather than a text >editor, since it seems more like MS Word than, say, Notepad. No? True. You are correct. Poor choice of phrase on my part.
And in regard to the "Skit's Law" surmise.. It was more an expectation of the imminent application of Murphy's law - if I was about to make comments about use of English, my expectation was that in short course, I would make a spectacular, public and noteworthy misuse of that very language. "Cover my a.s in advance".
But.. (now that Wikipedia page finally came up) yep! That's it, in a nutshell! I had not realised the specialised* form of it existed. ;-)
* And for those who want to whine about the 'z' you expect to see in that word. Go for it, & watch me not care..
 Signature Andrew Thompson http://www.athompson.info/andrew/
blmblm@myrealbox.com - 16 Aug 2007 08:14 GMT > >[ snip ] > > [quoted text clipped - 17 lines] > That's it, in a nutshell! I had not realised the specialised* > form of it existed. ;-) I know about it because Skitt is a regular in alt.usage.english, where I also lurk and sometimes post.
> * And for those who want to whine about the 'z' you > expect to see in that word. Go for it, & watch me not > care.. No problem here. Now, if you were to mix UK and US spellings, that might raise a hackle or two, but strictly one or the other -- there are better things to argue about, maybe.
 Signature B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor.
Real Gagnon - 14 Aug 2007 03:05 GMT > Runtime.getRuntime().exec("my excel location") Try
class StartExcel { public static void main(String args[]) throws java.io.IOException { // Win XP Runtime.getRuntime().exec("cmd /c start excel.exe"); } }
if you want to load a sheet at startup
class StartExcel { public static void main(String args[]) throws java.io.IOException { // Win XP Runtime.getRuntime().exec("cmd /c start /path/sheet.xls"); } }
Bye.
 Signature Real Gagnon from Quebec, Canada * Java, Javascript, VBScript and PowerBuilder code snippets * http://www.rgagnon.com/howto.html * http://www.rgagnon.com/bigindex.html
Roedy Green - 14 Aug 2007 03:05 GMT On Mon, 13 Aug 2007 21:38:43 -0000, "julielaurek@gmail.com" <julielaurek@gmail.com> wrote, quoted or indirectly quoted someone who said :
>So I was using Runtime.getRuntime().exec("my excel location") to >launch Excel on my PC. However, my excel is found in a folder called [quoted text clipped - 4 lines] >computer until it hits excel.exe, then use that excel file location >for the rest of a program? This is windows idiocy. Someday Bill Gates will be tortured for inflicting this sort of crap on the universe.
What you can do is ask users to build what I call "auxiliary path" entries in the registry so you can just use the exe name without path, or write a aux program to scan the disks to find excel and build the entry.
See http://mindprod.com/jgloss/registry.html
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|