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

Similar Messages

  • 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

  • Read All files in folder and sub folder

    Hi,
    i can read files in a folder,but not in a sub folders.can any one give me idea to read all files in the folder and its sub folder.
    Deepan

    Hi
    This code may help you
    Bliz
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.channels.FileChannel;
    public class CountFiles {
          * @param args
          * @throws IOException
          * Count files in <path> and all its subDirs
         public static String path = "c:";
         public static String src1 = "";
         public static FileChannel channel;
         public static int numF;
         public static int numD;
         public static void main(String[] args) throws IOException {
              countFiles(path);
              System.out.println("Number of files :\t"+numF);
              System.out.println("Number of dirs :\t"+numD);
         public static void countFiles(String strPath) throws IOException
              File src = new File(strPath);
              if (src.isDirectory())
                   numD++;
                   String list[] = src.list();
                   try {
                       for (int i = 0; i < list.length; i++)
                        src1 = src.getAbsolutePath() + "\\" + list;
                        File file = new File(src1);
                        try {
                   channel = new RandomAccessFile(file, "r").getChannel();
                        }catch(java.io.FileNotFoundException e){}
                        countFiles(src1);
                   }catch(java.lang.NullPointerException e){}
              else
              numF++;

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

  • Reading all files froma  folder

    Hi ,
    Does anyone know how to read the data from all text files in a given folder?
    I mean does text_io recongnises a certain sintax to do this?
    Thanks,
    Sandu

    Well
    I'm having problems initializing a java.lang.String as ora_java.jobject.
    I was able to import in forms my class ,(wich works ok when tested like standalone java class,it returns all the filenames from a folder),a package was generated on the form for it.
    But,I've got to pass it the folder name as a String.
    I've imported java.lang.String as ora_java.jobject,and a package was generated on the form.
    When I try to call string.new('c:\work');
    it won't compile,it says invalid reference to variable String.
    What should I do?Is there any predefined Type in ora_java package for java.lang.String?
    Thanks,
    Sandu

  • How to read list of all files in folder on application server?

    How to read list of all files in folder on application server?

    Hi,
    First get the files in application server using the following function module.
        CALL FUNCTION 'RZL_READ_DIR_LOCAL'
          EXPORTING
            name     = loc_fdir
          TABLES
            file_tbl = int_filedir.
    Here loc_fdir contains the application server path.
    int_filedir contains all the file names in that particular path.
    Now loop at int_filedir.
    OPEN DATASET int_filedir-name FOR INPUT IN TEXT MODE ENCODING  DEFAULT MESSAGE wf_mess.
    MESSAGE wf_mess.
        IF sy-subrc = 0.
          DO.
            READ DATASET pa_sfile INTO wf_string.
            IF sy-subrc <> 0.
              EXIT.
    endif.
    close datset int_filedir-name.
    endloop.

  • Read all Files from a Folder on Server

    Hi,
    Can anyone help me in finding if there's any way to read all files in a folder on the server?Any Function module or anything.
    Thanks

    On App server?  Try this sample program.
    report zrich_0001 .
    data: begin of itab occurs 0,
          rec(1000) type c,
          end of itab.
    data: wa(1000) type c.
    data: p_file type localfile.
    data: ifile type table of  salfldir with header line.
    parameters: p_path type salfile-longname
                        default '/usr/sap/TST/DVEBMGS01/data/'.
    call function 'RZL_READ_DIR_LOCAL'
         exporting
              name           = p_path
         tables
              file_tbl       = ifile
         exceptions
              argument_error = 1
              not_found      = 2
              others         = 3.
    loop at ifile.
      format hotspot on.
      write:/ ifile-name.
      hide ifile-name.
      format hotspot off.
    endloop.
    at line-selection.
      concatenate p_path ifile-name into p_file.
      clear itab.  refresh itab.
      open dataset p_file for input in text mode.
      if sy-subrc = 0.
        do.
          read dataset p_file into wa.
          if sy-subrc <> 0.
            exit.
          endif.
          itab-rec = wa.
          append itab.
        enddo.
      endif.
      close dataset p_file.
      loop at itab.
        write:/ itab.
      endloop.
    Regards,
    Rich Heilman

  • 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

  • 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?

  • To find total number of files inside folder

    Hai,
       In knowledge management is there any option to find total number of files inside folder...
        I also want to see the recently uploaded and modified documents in a seperate iview...
        Iam using NW2004s SP8..
        Very urgent..
        Waiting for a positive reply..
        Thanks&regards,
         Kiruthika.S

    Hi Kiruthika,
    1. You only need the configarchive if you don't want create all the KM configuration objects mentioned in the guide manually. So, just create the objects mentioned there and you don't need the configarchive
    Also, the scenario works also on 2004s.
    2. Please check this thread on how to show the total number of files inside a folder:
    https://forums.sdn.sap.com/thread.jspa?threadID=19610
    3. It would be nice if you would consider rewarding the time people like Saravanan spend to investigate and answer your question by assigning points via the colored stars.
    Best regards,
    Robert

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

  • Read all in a folder

    Hi. I want to read all files in a folder.
    For example: if in a folder I have the three next files
    file1, file4 and file13. Of course in the beginning I don't know
    which is its names because this is random. I need open all and then
    add its names in a list.
    The result should be:
    myList = [file1, file4, file13]
    thanks for your help

    You can use getNthFileNameInFolder() to figure out what files
    are in a
    folder.
    I prefer using FileXtra4 (not using D11)
    http://www.klkersten.com/xtras/index.html
    and if the file contains a list, save yourself some more
    hassle and use
    propSave (again, not using D11)
    http://pimz.com/?id=xtras&section=propsave
    Almudever wrote:
    > Hi. I want to read all files in a folder.
    > For example: if in a folder I have the three next files
    file1, file4 and
    > file13. Of course in the beginning I don't know which is
    its names because this
    > is random. I need open all and then add its names in a
    list.
    > The result should be:
    >
    > myList = [file1, file4, file13]
    >
    > thanks for your help
    >
    >

  • How to make button to format a HardDrive or USB, How to remove all files from folder, and How to delete a process in listbox with a textbox?

    Hello!
    Here's the question with explaniation: How can i format the USB or Drive by clicking a button what's meant for it?
    and the second question what's also in vb.net: How can i remove all files from folder ? 
     Here's the Look of program: *
    Using the PC button, it will delete the free space of the PC, do you guys/girls know where it's location?

    Example Code:
    Imports System.Runtime.InteropServices
    Imports System.IO
    Public Class Form1
    Dim CBoxDrives As New ComboBox
    WithEvents FButton As New Button
    <DllImport("shell32.dll")> _
    Private Shared Function SHFormatDrive(ByVal hwnd As IntPtr, ByVal drive As UInteger, _
    ByVal fmtID As UInteger, ByVal options As UInteger) As ULong
    End Function
    Private Enum SHFormatFlags As Integer
    SHFMT_ID_DEFAULT = &HFFFF
    SHFMT_OPT_FULL = &H1
    SHFMT_OPT_SYSONLY = &H2
    SHFMT_ERROR = &HFFFFFFFF
    SHFMT_CANCEL = &HFFFFFFFE
    SHFMT_NOFORMAT = &HFFFFFFD
    SHFD_FORMAT_FULL = 0 ' full format
    SHFD_FORMAT_QUICK = 1 ' quick format
    End Enum
    Private Sub FButton_Click_1(sender As System.Object, e As System.EventArgs) Handles FButton.Click
    If CBoxDrives.Text = "" Then
    MsgBox("No Drive Selected")
    Exit Sub
    End If
    Dim Iresult As ULong = SHFormatDrive(CType(Me.Handle.ToInt32, IntPtr), CUInt(Asc(CBoxDrives.Text.Substring(0, 1)) - Asc("A")), CUInt(SHFormatFlags.SHFMT_ID_DEFAULT), 1)
    End Sub
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Me.Size = New Size(200, 100)
    With FButton
    .Size = New Size(50, 25)
    .Location = New Point(5, 5)
    .Text = "Format"
    End With
    Me.Controls.Add(FButton)
    With CBoxDrives
    .Size = New Size(50, 25)
    .Location = New Point(75, 5)
    .DropDownStyle = ComboBoxStyle.DropDown
    End With
    Me.Controls.Add(CBoxDrives)
    Dim DrivesFound As Integer = 0
    Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
    Dim d As DriveInfo
    For Each d In allDrives
    If ((d.DriveType = DriveType.Fixed) Or (d.DriveType = DriveType.Removable)) AndAlso Environment.GetEnvironmentVariable("SYSTEMROOT").StartsWith(d.Name) = False Then
    CBoxDrives.Items.Add(d.Name)
    DrivesFound += 1
    End If
    Next
    CBoxDrives.SelectedIndex = DrivesFound - 1
    End Sub
    End Class

Maybe you are looking for

  • Adding Acrobat 9 Pro

    I have just upgraded Microsoft Office Pro to 2010 from 2007 - I want Acrobat 9 Pro available in all Office programs - Microsoft says - call Adobe - please advise Also I purchased a new tablet pc - can I install my Acrobat 9 Pro on it - I currently ha

  • Outgoing mail server will work on Iphone but not Mail on Macbook

    My POP account will send mail on my iphone no problem, but on the mail program on my macbook it times out. All the account information is identical. The mail program keeps telling the server does not support port 995, but on the Iphone it does. I hav

  • ECC 6.0 installation on external HD

    I have a dual boot laptop with XP and Win 2003 server. I have a 1 TB external HD connected to the laptop, on which i want to install ECC 6 and BI 7.0. I have installed Oracle and JDK as per requirement.But when SAP ECC 6.0 installation starts it does

  • STOCK REACHED MINIMUM LEVEL THEN NEED REMAINDER FROM SYSTEM

    Hi Experts, Actually i want when the stock reached minimum level then we need to get the remainder or intimation fro the system. I want in detail about this question. i gone through google also  but i m not getting correct solution for this. Thanks,

  • Bpelx:remove gives runtime error

    Hi, I want to remove an element from an xml variavble. According to documentation I use the following syntax: <assign name="VerwijderBSN"> <bpelx:remove> <bpelx:target variable="inputVariable" part="payload" query="/client:SBVaststellenPersoonssetPro