Use JFilechooser to read all Files inside Directory

Hello gang!
I was wondering how to modify the code below to allow it to select Files AND Directories. If it selects a Directory, I want it to be able to look in that directory for all .jpg files, and return a list of all the jpg files to me. It does not have to search in any subfolders..only the folder that the user selects with the jfilechooser.
File defaultDirectory = new File("C:\\"); // Set Default Directory
JFileChooser fc = new JFileChooser( defaultDirectory );
fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
fc.setAccessory(new ImagePreview(fc));
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showDialog(currentFrame, "Attach");
if (returnVal == JFileChooser.APPROVE_OPTION)
File files[] = fc.getSelectedFiles();
for (int b=0; b < files.length; b++)
String pathName = files.getAbsolutePath();
storeInfoRef.setFiles(pathName);
defaultDirectory = files[0];
fc.setCurrentDirectory( defaultDirectory ); // New Default Dir
else
{ System.out.println("Attachment cancelled by user"); }

I have solved my problem. For anyone with a similar problem here is the code I added since my last post
JFileChooser fc = new JFileChooser( defaultDirectory );
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
fc.setAccessory(new ImagePreview(fc));
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showDialog(currentFrame, "Attach");
if (returnVal == JFileChooser.APPROVE_OPTION) //If Button Pressed
File files[] = fc.getSelectedFiles(); // Get Users Selections
for (int b=0; b < files.length; b++) // For Each Selection
if ( files.isDirectory() ) // If User Selected a Directory
File[] folderFiles = files[b].listFiles(); // Get contents of folder
log.append("For folder: " + files[b].getName() + "." + newline);
int count=0; // Keeps Count of # of Image Files
for ( int i=0; i < folderFiles.length; i++ ) // For each item in folder
if( (folderFiles.getName().endsWith(".jpg") ) || //If file is an Image
(folderFiles[i].getName().endsWith(".jpeg")) ||
(folderFiles[i].getName().endsWith(".bmp") ) ||
(folderFiles[i].getName().endsWith(".gif") ) ||
(folderFiles[i].getName().endsWith(".tif") ) ||
(folderFiles[i].getName().endsWith(".tiff") ) )
System.out.println( folderFiles[ i ].getName() );
String pathName = folderFiles[i].getAbsolutePath(); //Get Path of File
storeInfoRef.setFiles(pathName); //Save Path of File
log.append(" Attaching file: " + folderFiles[i].getName() + "." + newline);
count++; //Increase Counter
if ( count == 0 ) // If No Images
log.append( " There are no Image Files to Attach" );
else if ( files+.isFile() ) // If User Selected File(s)
String pathName = files[b].getAbsolutePath();
storeInfoRef.setFiles(pathName);
System.out.println ("File Size: " files[b] +" is "+files.length() );
log.append("Attaching file: " + files[b].getName() + "." + newline);
defaultDirectory = files[0];
fc.setCurrentDirectory( defaultDirectory ); // New Default Dir
else
{ log.setText("Attachment cancelled by user." + newline); }

Similar Messages

  • Reading all files on directory using "utl_file" package...

    I need to read all files in directory via PL/SQL. I don't know
    name files (are data dynamics create for automation system),
    only I know your extensions.
    Can I do this using the package "utl_file" or I need to create
    program in another language (C, C++, for example)?
    Any ideas...
    Thanks.

    Hi,
    you can't do that with the UTL_FILE package (it can't retrieve
    file names).
    A very simple solution would be, if you created on OS-level a
    file which contains the filenames of directory and then read this
    file using UTL_FILE. With the information on all file names you
    can enter a loop which opens and reads all files again using
    UTL_FILE.
    A more mundane solution could be to use the features on the iFS.
    Cheers
    Gerald

  • How to Read all files inside resource Folder inside Jar?

    I have a Jar file,,,, The program reads for resource files in the resource folder inside the Jar. I want my program to read all files inside this folder without knowing the names or the number of files in the folder.
    I am using this to make an Applet easy to be updated with spicific files. I just want to add a file inside the resource folder and Jar the program and automatically the program reads what ever is in there!!
    I used the File class to get all file names inside the resource folder. it works fine before Jarring the program. After I jar I recieve a URI not Herarichy Exception!!
    File fold=new java.io.File(getClass().getResource(folder).toURI());
    String[] files=fold.list();
    I hope the question is clear!!

    How to get the directory and jar file that you class resides in:
    // returns path and jarfile (ex: /home/mydir/my.jar)
    public String getJarfileName()
            // Get the location of the jar file and the jar file name
            java.net.URL outputURL = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
            String outputString = outputURL.toString();
            String[] parseString;
            int index1 = outputString.indexOf(":");
            int index2 = outputString.lastIndexOf(":");
            if (index1!=index2) // Windows/DOS uses C: naming convention
               parseString = outputString.split("file:/");
            else
               parseString = outputString.split("file:");
            String jarFilename = parseString[1];
           return jarFilename;
    }If your my.jar was in /home/mydir, it will store "/home/mydir/my.jar" in jarFilename.
    note: getLocation returns "file:/C:/home/mydir/my.jar" for Windows/DOS and "file:/home/mydir/my.jar" for windows, thus why I look for the first and last index of the colon so I can correctly split the string.
    If you want to grab a file in the jar file and get an InputStream, do the following:
    import java.io.*;
    import java.util.Enumeration;
    // jar stuff
    import java.util.jar.*;
    import java.util.zip.ZipEntry;
    public class Jaris
       private JarFile jf;
       public Jaris(String jarFilename) throws Exception
           try
                           jf = new JarFile(jarFilename);
           catch (Exception e)
                jf=null;
                throw(e);
       public InputStream getInputStream(String matchString) throws Exception
           ZipEntry ze=null;
           try
              Enumeration resources = jf.entries();
              while ( resources.hasMoreElements() )
                 JarEntry je = (JarEntry) resources.nextElement();
                 // find a file that matches this string from anywhere in my jar file
                 if ( je.getName().matches(".*\\"+matchString) )
                    String filename=je.getName();
                    ze=jf.getEntry(filename);
          catch (Exception e)
             throw(e);
          InputStream is = jf.getInputStream(ze);
          return is;
       // for testing the Jaris methods
       public static void main(String[] args)
          try
               String jarFilename=getJarfileName();
               Jaris jis = new Jaris(jarFilename); // this is the string we got from the other method listed above
               InputStream is=jis.getInputStream("myfile.txt"); // can be used for xml, xsl, etc
          catch (Exception e)
             // this is just a test, so we'll ignore the exception
    }Happy coding! :)
    Doc

  • Reading all files in directory

    Hi
    I need to read all the files inside a directory where my app resides. I have the following:
    File file = new File(args[0]);
    Reader reader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(reader);
    This works fine for one file, but i have many files I would like to
    read in this directory. I was hoping I could just do:
    java MyApp *
    but it doesn't work. thanks in advance for any help.
    J.

    rtfm
    http://java.sun.com/products/jdk/1.1/docs/api/java.io.File.html#list()

  • Reading All Files inside folder codeBase, Applet!

    I have an applet, placed in a Jar file.. everything is ok,,
    I have a resource folder outside the Jar, which has some files.
    how can I read what is inside the resource folder, which is located outisde the Jar, without having their addresses before hand!!
    in short, I would like the applet to open the resource folder, get an array of all files in the folder, and then reads them.
    I tried encapsulating the getCodeBase().toURI() with a File Object.
    But when I call the file.list() it throws an AccessControlException
    thank you.

    Here is a simple example of using ftp to obtain file list using Jakarta common net package.
    // ftp - related imports
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPReply;
    // main method
              FTPClient ftpClient = null;
              try {
                   ftpClient = new FTPClient();
                   ftpClient.connect("REMOTE_HOST", "remote port, use 21 in common case");
                   System.out.print(ftpClient.getReplyString());
                   int reply = ftpClient.getReplyCode();
                   if(!FTPReply.isPositiveCompletion(reply)) {
              ftpClient.disconnect();
              System.err.println("FTP server refused connection.");
              System.exit(1);
                   boolean isLoggedIn = ftpClient.login("your login", "your pass");
                   ftpClient.changeWorkingDirectory("/your remote dir/");
                   String[] fNames = ftpClient.listNames();
                   for (int i = 0; i < fNames.length; i++) {
                        System.out.println(fNames);
                   ftpClient.logout();
              } catch (IOException e) {
                   e.printStackTrace();
              } finally {
                   if(ftpClient.isConnected()) {
                        try {
                             ftpClient.disconnect();
                        } catch(IOException ioe) {
                             ioe.printStackTrace();
    System.exit(0);

  • How to read a files in directory and its subdirectories

    I wants to read all files in directory, its subdirectory and further till end the files in the subdirectory of subdirectories.
    I have some idea the I can do this by using recursive function, using the functions isDirectory(), File.list() etc.
    How much you can please help me. (via code of logic)

    import java.io.*;
    import java.net.*;
    public class MyCon
    public static void main(String args[]) throws
    IOException
    File file=new File("c:/");
    openDirectory(file,"");
    System.in.read();
    static void openDirectory(File file,String indent)
    String[] string=file.list();
    String path=file.getAbsolutePath();
    for(int i=0;i<string.length;i++)
    File temp=new File(path+"/"+string);
    if(temp.isDirectory())
    openDirectory(temp,indent+" ");
    else
    System.out.println(indent+temp.getName());

  • How  to read all files  under a folder directory in FTP site

    Hi Experts,
    I use this SQL to read data from a file in FTP site. utl_file.fopen('ORALOAD', file_name,'r');
    But this need to fixed file name in a directory. However, client generate output file with auto finename.
    SO do we have any way to read all file by utl_file.fopen('ORALOAD', file_name,'r');
    We need to read all file info. because client claim for security issue and does not to overwirte output file name,
    we must find a way to read all file in output directory.
    Thanks for help!!!
    Jim

    If you use Chris Poole's XUTL_FTL package, I believe that contains functions that allows you to query the directory contents.
    http://www.chrispoole.co.uk/apps/xutlftp.htm
    Edited by: BluShadow on Jan 13, 2009 1:54 PM
    misread the original post

  • HTML  Parsers and reading all files in a directory

    Hello all,
    I was wondering if there was a html parser included in java. I am writing a program where I want to be able to search all the files in a directory tree for a particular string. I was able to read one file in a single directory but not in any other directory. How would I go about writing code to be able to access all files in directory that has multiple sub folders.
    Also, when I started to write my program I tried to use the DOM XML Parser to parse my html page. My logic behind this decision was that if you look at html code it is an xml document. But as I was trying to run my program I noticed that I had to convert my html document into xml format. I really don't want to have to build my own html parser. Is there a html parser that is included in Java. Oh my program is just your basic text program. No interfaces.
    Thanks for any help that you can provide
    Hockeyfan

    a particular string. I was able to read one file in
    a single directory but not in any other directory.
    How would I go about writing code to be able to
    access all files in directory that has multiple sub
    folders.
    You can do that several ways.
    Most likely you'll end up with some sort of recursive iteration over the directory tree.
    Not hard to write, somewhat harder to prevent memory problems if you end up with a lot of data.
    Also, when I started to write my program I tried to
    use the DOM XML Parser to parse my html page. My
    logic behind this decision was that if you look at
    html code it is an xml document. But as I was
    trying to run my program I noticed that I had to
    convert my html document into xml format. I really
    don't want to have to build my own html parser. Is
    there a html parser that is included in Java. Oh my
    program is just your basic text program. No
    interfaces.
    A VALID xhtml document is a valid XML document.
    Problem is that most HTML isn't xhtml.
    Another problem is that most HTML is fundamentally broken even to its own standards (which have always been based on SGML on which XML is also based).
    Browsers take that into account by being extremely lax on standards compliance and effectively making up tags as they go along to fill in the missing ones in the trees they parse.
    That's however not a standardised process and each browser handles it differently (and as a result most html will render differently in different browsers).
    Java contains a simple HTML parser in Swing, but it's primitive and will only parse a subset of HTML 2.0.
    There are almost certainly 3rd party libraries out there that can do better, both free and/or commercial.

  • Read all files in chield and their chield's directory

    I am trying to make a program which read all files in a directory and its subdirectory like scandisk program of window's operating system. I gause this I can do via recursion using the methods isDirectory(), File.list() etc. Please help me to implement this problem in code.
    Regards
    yogesh

    you guys should collaborate,
    http://forum.java.sun.com/thread.jsp?forum=4&thread=153110&start=0&range=30#443719

  • Newbie question -  How to read all files for a backup

    Hello all,
    I have two users on my iMac. I am an administrator and the other user is a Standard user.
    From my account, I wish to run backup software that will backup the entire "User" directory. The problem I am having is that when I run the backup software (fyi: iBackup),
    it complains that it cannot read the files in the other user's account.
    I notice that when I browse to the other user's account, all the directories in their home folder are locked.
    How can I run my backup software so that it can read all files in the User directory?
    Thank you kindly!
    Jeff
    17" iMac Core Duo   Mac OS X (10.4.6)  

    Hi kneecarrot !
    I don't know if this will suit your needs, but one easy way of backing up other user's stuff is via the terminal . If you have an admin accountm just use:
    sudo ditto -rsrcFork /Users /Volumes/"nameof_anotherharddrive"/Users
    This will perform an identical clone of all your users home direcories for backup purposes. To restore the bkd'up files, just reverse the lines:
    sudo ditto -rsrcFork /Volumes/"nameof_anotherharddrive"/Users /Users
    ATTENTION: Be aware that it will restore the files to the exact structure and contents it was when backed up, erasing all new and modified files!! You may however copy just the files/folders you want to recover, e.g.:
    sudo ditto -rsrcFork /Volumes/"nameof_another_harddrive"/Users/"usera"/Documents /Users/"user_a"/Documents
    IMPORTANT: As with all terminal commands... be careful, think twice and double-check the syntax. You may want to test with non-critical stuff or demo user accounts first.
    Good luck,
    Michael
    MacBook Pro   Mac OS X (10.4.6)   2 Gig RAM

  • How to read, write file inside the JAR file?

    Hi all,
    I want to read the file inside the jar file, use following method:
    File file = new File("filename");
    It works if not in JAR file, but it doesn't work if it's in a JAR file.
    I found someone had the same problem, but no reply.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=180618
    Can you help me ? I have tried this for all night !
    Thanks in advance
    Leo

    If you want to read a file from the JAR file that the
    application is packaged in (rather than a separate
    external JAR file) you do it like this ...
    InputStream is =
    ClassLoader.getSystemResourceAsStream("filename");Better to use
    this.getClass().getClassLoader().getResourceAsStream();
    From a class near to where the data is. This deals with multiple classloaders properly.

  • Build Applicatio​n with all files inside .exe

    Hello,
    I have a labview project consisting of a few classes and subvi's. Nothing really special. Now when i try to build an .exe file, i get the .exe, an application.ini, an Application.aliases and an data folder (has the classes and dll's within). What i want however is the .exe file with all files inside. So that at the test setup, there is only one file on de dekstop, and not 4. Is it possible to do that?
    Greetings wcm 

    LabVIEW 2009 and later have a build option (set on per default) that embeds all the classes inside the executable file.
    The ini file will always be created, however you can delete it during startup of your executable.
    I think you don't need the data folder since that has some DLL already present on your system.
    However my advise is to create an installer that puts the executable (and the other files) inside the program files folder. And the installer can create a shortcut to the executable.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • How to count all files inside a disk?

    Hi,
    is there any free app to count all files inside a hard disk or volume without open all volumes and folders?
    Not the size, but the number of files.
    Thank you very much.

    Disk Utility displays a full drive folders and files
    Finder with Show Status Bar, displays folder items at the bottom the Finder window
    Do you require further information than these?

  • How to delete a READ ONLY file from Directory

    Hi Friends,
    how to delete a READ ONLY file from Directory , file is in my system only.
    Please help me .
    note: its read only file.
    Thank you.
    Karthik.

    hI,
    try with this statement.
    delete dataset <datasetname>.
    this will definitely work.
    Regards,
    Nagaraj

  • I used tag to show PDF file inside my JSP page, It is working properly in IE but nothing shows in Mozilla. What should I do?

    I've used to display a PDF file inside my JSP page. It is working fine in IE. However, many of users of this application are using Mozilla and the platform is Ubuntu so it is vital that the file is shown in Mozilla as well. How can I solve this problem.
    == This happened ==
    Every time Firefox opened
    == I run my jsp page

    Such conditional code will only work in IE and not in other browsers like Firefox.
    You can ask questions and advice about web development at the mozillaZine Web Development/Standards Evangelism forum.<br />
    A good place to ask questions and advice about web development is at the mozillaZine Web Development/Standards Evangelism forum.<br />
    The helpers at that forum are more knowledgeable about web development issues.<br />
    You need to register at the mozillaZine forum site in order to post at that forum.<br />
    See http://forums.mozillazine.org/viewforum.php?f=25

Maybe you are looking for

  • Ipod mini versus windows vista

    i just got a used ipod mini (4g version). i used the installer disc that came with it, udated itunes to 9.1, plugged my ipod in and nothing. the ipod comes up charging and on the main menu, but other than that, goose egg. is vista or windows media pl

  • Is there a way to make suggestions to Apple?

    With the iPhone being so popular and many reports of it being stolen, the Find My iPhone can be a great feature.    Except that the perp can turn it off!!!  What good is the feature then?   How can I suggest to Apple that they put a pass code lock or

  • Can i set up a separate folder in 4s inbox

    Can I establish a folder in my mail inbox so that I can save certain email on my 4S? All I see is; inbox, drafts, sent, trash. I would like to establish a "save" folder. Thanks.

  • Archive log file size is varying in RAC 10g database.

    ---- Environment oracle 10g rac 9 node cluster database, with 3 log groups for each node with 500 mb size for each redo log file. Question is why would be the archive log file size is varying, i know when ever there is log file switch the redo log wi

  • Issue with Safari (2 and 3) keeping orderly text on webpages

    PowerMac G5 Dual 2 GHz, OS X 10.4.10 On opened webpages, the text is becoming blurred after a few minutes and finally is becoming unreadable. On moving the scrollbar it even disappears and is multiplied or replaced by all kinds of useless figures. I