Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2006

Tip: Looking for answers? Try searching our database.

Obtain file path and file name using file chooser

Thread view: 
bH - 28 Nov 2006 03:53 GMT
Hi All,
I want to obtain both file  "path" and the filenamed  MyText.txt ....as
in "C:\Documents
and Settings\bH\Desktop\MyShowWithFrame\MyText.txt"

I have tried to discover the options shown in How to Use File Choosers
(The Java™ Tutorials  Creating a GUI with JFC-Swing Using Swing
Components).htm

I cannot understand what options should be shown as but this does not
work.

Program snip:
    JButton opnButton = new JButton("Open a Text File...");
    buttonPanel.add(opnButton);
    opnButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       int returnVal = fc.showOpenDialog(FileChooserDemo.this);
       fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
       if (returnVal == JFileChooser.APPROVE_OPTION) {
          File file = fc.getSelectedFile ();
           strngFileName =  file.getName();
       }
     }
   });

       });

TIA
bH
Andrew Thompson - 28 Nov 2006 04:40 GMT
> Hi All,
> I want to obtain both file  "path" and the filenamed  MyText.txt ....as
[quoted text clipped - 7 lines]
> I cannot understand what options should be shown as but this does not
> work.

Is it lazy?  Or to put that another way 'it doesn't work'
tells us very little.  Please describe in detail, what you
see on-screen, what happened off-screen (with debug
statements and such) and what you expected to happen.

However - taking a wild stab..

> Program snip:
>      JButton opnButton = new JButton("Open a Text File...");
[quoted text clipped - 6 lines]
>            File file = fc.getSelectedFile ();
>             strngFileName =  file.getName();

..if I guess correctly, you might try something like

 strngFileName =  file.getPath() +
   System.getProperty("file.separator") +
   file.getName();

Having said that, it seems strange you are dealing with
String's, when you have a File object (which is an object
that is already one step closer to getting an input/output
stream, than a String that represents a File).

Andrew T.
bH - 28 Nov 2006 19:55 GMT
> > Hi All,
> > I want to obtain both file  "path" and the filenamed  MyText.txt ....as
[quoted text clipped - 38 lines]
>
> Andrew T.

Hi Andrew,
Your guess was correct and your advice helpful. Now I am in another
difficulty.

Because I am connecting with a printer after locating a file address
when I am  using the file chooser, all the file separators are "\" but
should be "/". I have tested a method: one that looks at the individual
char in the line but have not been able to represent the "\" because it
is an escape character.

A sample of the output from the chooser:
"C:\Documents and Settings\bH\Desktop\MyPrinter
WithFrame\MyText.txt\MyText.txt"
Needs to be:
"C:/Documents and Settings/bH\Desktop/MyPrinter
WithFrame/MyText.txt/MyText.txt"

TIA.
bH
Steve W. Jackson - 28 Nov 2006 21:29 GMT
> > > Hi All,
> > > I want to obtain both file  "path" and the filenamed  MyText.txt ....as
[quoted text clipped - 58 lines]
> TIA.
> bH

It's not clear what "connecting with a printer" has to do with anything.  
Printing in Java doesn't involve files.  It involves the Printable and
Pageable interfaces and sending a "picture" to the printer via
appropriate APIs.

But if you're seeking a way to refer to a File object after it's been
selected using a JFileChooser, you should look into the java.io.File API
a bit more closely.  It includes a couple of possible useful methods,
which are toURL and toURI.  You might be better off using the latter.  
And doing so will result in a URI that encodes any spaces or other
"special" characters, as well as using "real" slashes instead of those
horrid backslash things Microsoft hoisted upon you.

= Steve =
Signature

Steve W. Jackson
Montgomery, Alabama

Andrew Thompson - 28 Nov 2006 21:36 GMT
> > > I want to obtain both file  "path" and the filenamed  MyText.txt ....as
> > > in "C:\Documents
> > > and Settings\bH\Desktop\MyShowWithFrame\MyText.txt"

...
> > > Program snip:
...
> > >         int returnVal = fc.showOpenDialog(FileChooserDemo.this);
> > >         fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
> > >         if (returnVal == JFileChooser.APPROVE_OPTION) {
> > >            File file = fc.getSelectedFile ();
> > >             strngFileName =  file.getName();
...
> >   strngFileName =  file.getPath() +
> >     System.getProperty("file.separator") +
> >     file.getName();
..
> Because I am connecting with a printer after locating a file address
> when I am  using the file chooser, all the file separators are "\" but
> should be "/".

Aaaah.. my original answer was ..incomplete.

I was prodding you in the direction (I thought) this
code needs to go, but since we've already arrived 'there',
let's take it a bit further.

1) For starters, the way I constructed that file was
sloppy and inefficient.  The *best* way to create a File
in a given directory is to use the File contstructor to
create a File based on ..
 new File(File parent, File theFile)
..to automatically get the correct separator.

2) I cannot see why the code needs to be manipulating the
String name of the File(s) at all.  Don't the later methods
accept files as parameters?  If that is the case, you can
simply hand the later methods 'the file', and be done with it.

3) If the String name of the File *is* actually of interest, I
am pretty sure that File has some methods to produce
the entire path and filename.  Check the API..

Andrew T.
bH - 01 Dec 2006 13:48 GMT
> > > > I want to obtain both file  "path" and the filenamed  MyText.txt ....as
> > > > in "C:\Documents
[quoted text clipped - 40 lines]
>
> Andrew T.

/* Tested  using Win2k with NT, with Java jdk1.5.0_05 and a Canon
Printer.
* This program will print "m.txt", "t.java", "ms.html" source code as
long as  the
*  files are in the same folder as this program OR if the path and
name is shown.
*
* The printer output  starts at the very top of the page, full to the
very bottom
* of the page, full left and right. However, indents are shown.
* Then  similarily on to the second page if needed.  Printing stops on
the page
* at  where ever the stream stops.  To get the paper out of the
printer:
* press right button on the Canon Printer.
*/

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.*;

public class UseFileChooser_TxtPrint extends JFrame  {
 JButton buttnOne, buttnTwo;
 String  strFileName= "";

 public static void main(String[] args) {
   UseFileChooser_TxtPrint  UseFileChooser_TxtPrint1 = new
UseFileChooser_TxtPrint();
 }

 public UseFileChooser_TxtPrint() {
   super("Print Text . . .");

   final JFileChooser fc = new JFileChooser();

   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel dataPnl = new JPanel();
   JPanel btnPnl = new JPanel();
   JLabel lbleFileName = new JLabel("Start With Chooser  Button Then
Printer Button  >>> ");
   buttnOne = new JButton("Chooser Button");
   buttnTwo = new JButton("Print Button");

   dataPnl .setLayout(new  GridLayout(2, 2));
   dataPnl .add(lbleFileName);

   btnPnl.add( buttnOne);
   btnPnl.add( buttnTwo);

   this.getContentPane().add(dataPnl, BorderLayout.NORTH);
   this.getContentPane().add(btnPnl, BorderLayout.SOUTH);
   setSize(400, 100);
   setVisible(true);
   buttnOne.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (e.getSource() == buttnOne) {
         int returnVal = fc.showOpenDialog(UseFileChooser_TxtPrint
.this);
         File file = fc.getSelectedFile();
         strFileName = file.getPath();
       }
     }
   });
   buttnTwo.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent h) {
       if (h.getSource() == buttnTwo) {
         System.out.println("Now Printing File " + strFileName);
         try {
           InputStream is = new BufferedInputStream(
                                                    new
FileInputStream(strFileName));
           // Find the default service
           DocFlavor flavor =DocFlavor.INPUT_STREAM.AUTOSENSE;

           PrintService service =
PrintServiceLookup.lookupDefaultPrintService();

           // Create the print job
           DocPrintJob job = service.createPrintJob();
           Doc doc = new SimpleDoc(is, flavor, null);

           // Monitor print job events for use for the implementation
of PrintJobWatcher,

           PrintJobWatcher pjDone = new PrintJobWatcher(job);

           // Print it
           job.print(doc, null);

           // Wait for the print job to be done
           pjDone.waitForDone();

           // It is now safe to close the input stream
           is.close();
         } catch (PrintException e) {
         } catch (IOException e) {
         }
         System.out.println("Task Completed" );
       }
     }
   } );
 }
 class PrintJobWatcher {
   // true iff it is safe to close the print job's input stream
   boolean done = false;

   PrintJobWatcher(DocPrintJob job) {
     // Add a listener to the print job
     job.addPrintJobListener(new PrintJobAdapter() {
       public void printJobCanceled(PrintJobEvent pje) {
         allDone();
       }
       public void printJobCompleted(PrintJobEvent pje) {
         allDone();
       }
       public void printJobFailed(PrintJobEvent pje) {
         allDone();
       }
       public void printJobNoMoreEvents(PrintJobEvent pje) {
         allDone();
       }
       void allDone() {
         synchronized (PrintJobWatcher.this) {
           done = true;
           PrintJobWatcher.this.notify();
         }
       }
     });
   }
   public synchronized void waitForDone() {
     try {
       while (!done) {
         wait();
       }
     } catch (InterruptedException e) {
     }
   }
 }
}
bH - 01 Dec 2006 13:50 GMT
> > > > I want to obtain both file  "path" and the filenamed  MyText.txt ....as
> > > > in "C:\Documents
[quoted text clipped - 40 lines]
>
> Andrew T.

Hi All,
Thanks for your help. Your suggestions have been most helpful.
I have revised a earlier program which is a JTextField input now to be
a chooser input.

bH


Free Magazines

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

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.