Re: Q: easiest possible file select dialog
RedGrittyBrick (RedGrittyBrick@SpamWeary.foo) wrote:
: Malcolm Dew-Jones wrote:
: > Hello
: >
: > I have some command line java utilities running on windows NT/XP/etc and I
: > would like them to pop up a file select dialog box if no file is entered
: > as a parameter.
: >
: >
: > I have seen an example using JFileChooser but even though this says it
: > takes just two lines, in fact it appears to assume you already have a gui
: > app (awt, swing ?) and the examples have a whole bunch of code before they
: > gets to the part where you get to pop up the dialog to ask for a filename.
: >
: > Is there more trivial way to popup a file select dialog from a java
: > command line program on Windows?
: >
: Something that pops up a dialog is, by definition, not a command line app.
Well I guess that's true by definition, but these utilities do things like
read standard input and write standard output (or whatever it's correctly
called in Java) and are ammenable to uses like
perl Gen_Data | java UseNiceJavaLib config | grep something > saveit
which is using what I would normally call "command line utilities". I
want the java program to be able to pop up a file dialog because that's by
a convenient general purpose way for the user to specify a file name
sometimes - and it works just fine in other languages.
: public class ChooseApp {
: public static void main(String[] args) {
: String filename;
: if (args.length > 0)
: filename = args[0];
: else {
: JFileChooser fc = new JFileChooser();
: int returnVal = fc.showOpenDialog(null);
: if (returnVal == JFileChooser.APPROVE_OPTION) {
: filename = fc.getSelectedFile().getName();
: } else {
: System.out.println("Cancelled.");
: System.exit(1);
: }
: }
: System.out.printf("You chose file '%s'\n", filename);
: }
: }
That works great thanks, and in case I want to re-read this a year from
now, I put
import java.io.*;
import javax.swing.JFileChooser;
at the top, and System.exit(0); near the end or it doesn't exit (I guess
the dialog needs to be explicitly destroyed or such like(?)).
Thanks.