Is It Possible to Make Java Find a File on Your Computer?

J

julielaurek

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
 
M

Manish Pandit

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


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
 
A

Andrew Thompson

'search disk for Excel'
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, ...

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).

--
Andrew Thompson
http://www.athompson.info/andrew/

Message posted via JavaKB.com
http://www.javakb.com/Uwe/Forums.aspx/java-general/200708/1
 
K

Knute Johnson

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

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");
}
}
 
R

Real Gagnon

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.
 
R

Roedy Green

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?

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
 
J

Jeff Higgins

Knute said:
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
 
L

Lew

Jeff said:
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.

Would this work to bring up Open Office if I don't have Excel on my machine?
 
J

julielaurek

Would this work to bring up Open Office if I don't have Excel on my machine?

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
 
K

Knute Johnson

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?

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.
 
J

Jeff Higgins

Lew said:
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
 
J

julielaurek

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

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
 
J

Jeff Higgins

julielaurek said:
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.
 
A

Andrew Thompson

Lew said:
[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?

..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*.)

--
Andrew Thompson
http://www.athompson.info/andrew/

Message posted via JavaKB.com
http://www.javakb.com/Uwe/Forums.aspx/java-general/200708/1
 
R

Real Gagnon

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");
}
}

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.
 
K

Knute Johnson

Jeff said:
julielaurek said:
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.

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.
 
K

Knute Johnson

Andrew said:
Lew said:
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?

.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*.)

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.
 
L

Lew

Knute said:
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.

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.
 
K

Knute Johnson

Lew said:
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.
 
B

blmblm

Lew wrote:

[ 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 ]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top