Reading filenames

Hello,
I am making a program that requires me to read in all the filenames that are in a certain directory and output them into a file. I think i will be able to output them no problem, but how do I get the names of the files?
thanks,
evan

There is a method in the File class which returns an array of File objects, which are the Files within the directory specified by the original file:
File mydir=new File("C:/Windows");
File[] f=mydir.listFiles();f is now an array of all the files in the C:/windows directory!
You will need to iterate the array, and on each file object call getName() which returns the filename. E.g.:
File f=new File("C:/Windows/some folder/myTextFile.txt");
System.out.println(f.getName());will print out 'myTextFile.txt' to the standard output.

Similar Messages

  • Read filename of email attachment for sender mail adapter

    Hi All,
    We have a requirement to read filename of email attachment received from Sender email adapter and send details to SAP by Proxy call.
    Can we retrieve the filename of email attachment ?
    Any help on this will be really useful.
    Regards,
    Ashish

    Hi,
    >>>Can we retrieve the filename of email attachment ?
    Please see the below link, it might be useful to you.
    http://wiki.sdn.sap.com/wiki/display/XI/AdapterModulePI7.0GetAttachmentName
    Regards,
    P.Rajesh

  • Read Filename form Adapter-Specific Message Attributes in Java Mapping

    Hi,
    I have scenario File to Mail adapter. How can i read filename from Adapter-Specific Message Attributes
    in java mapping.
    Thank you and Best regards
    Fernand

    Hello Fernand,
    Are u using DOM or SAX parser?
    In any case just put the Dynamic config code in the execute function or the other option is to define it as a private functionand call it in the execute,My personal advice would be the former.
    Just put this code in ur java mapping
    As fellow sdn ers have mentioned there is no need of the container method,just initialise the set param method and use it in the dynamice config code as follows
    public class YourClass implements StreamTransformation
         private Map map;
    public void setParameter(Map param)
         map = param;
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException
                   DynamicConfiguration conf =(DynamicConfiguration) map.get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
                   DynamicConfigurationKey KEY_FILENAME =DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File","FileName");
    // read value
    File = conf.get(KEY_FILENAME);
    Now just call File in the mapping program,
    Should help u out 
    Regards,
    Tauseef

  • How to read Filename using FileAdapter

    I am trying to write some xml files using FileAdapter of SOA11g. For that I have created synchronous BPEL process.
    My xyz.jca file looks something like this:
    <endpoint-interaction portType="Write_ptt" operation="Write">
    <interaction-spec className="oracle.tip.adapter.file.outbound.FileInteractionSpec">
    <property name="PhysicalDirectory" value="/mnt/vol_ora_SOADEV1_apps_01/DevCsvFiles/Inventory"/>
    <property name="Append" value="false"/>
    <property name="FileNamingConvention" value="FileTemp%SEQ%.txt"/>
    <property name="NumberMessages" value="1"/>
    </interaction-spec>
    </endpoint-interaction>
    Now the problem is I want to know the filename which is just being written by this Adapter. I want to use that filename later in my code.
    I tried using filename property in invove activity, but I am unable to read filename after its written to disk.

    Got right way to do it. Create one variable eg varFileName, assign some value eg. "Filenamexyz.ext" and refer to that variable (set properties of invoke activity jca.file.filename as varFileName and type 'Input')in Invoke activity invoking read adapter .

  • Reading filenames with characters other than a-z

    Hi!
    My problem is that I'm writing very simple integration that only transfers files around. Problem is that some directories and filenames have for example scandinavien characters.
    Examples:
    D:\lähtevä\lähtö.xml
    Problem is that when I read files/directories via following code while in the D:\lähtevä folder:
    File dir = new File(fname);
    String[] chld = dir.list();
    if(chld == null){
    System.out.println("Specified directory does not exist or is not a directory.");
    System.exit(0);
    }else{
    for(int i = 0; i < chld.length; i++){
    String fileName = chld;
    System.out.println(fileName);
    variable "fname" would be "." given from command line when application starts up.
    Result is that all "ä" letters become "&#931;" characters. Other scandinavian letters are also messed up. I'm running on windows machine.
    What is the correct way to read filenames so that their country-specific characters are not messed up?

    Will this small test run correctly on your machine?
    public class ReadingFilesWithNonASCIINames {
        public static void main(String[] args) {
            String dirPath = "E:/lähtevä";
            String fName = "lähtö.txt";
            File directory = new File(dirPath);
            assert directory.exists();
            File file = new File(directory, fName);
            assert file.exists();
            //Now try to read it
            try {
                FileReader reader = new FileReader(file);
                int c;
                while((c = reader.read()) != -1) {
                    System.out.print((char)c);
            } catch (IOException e) {
                e.printStackTrace();
    }Compile it and run it with -ea flag. On my machine it ran without any problems (Windows XP, BE/fr locale, default encoding for files: System default -- windows-1252)

  • Javac can't read filename.java

    Hi
    my problem is that javac can't read filename.java
    i have saved the source code as filename.java under text document file type and i kept the capitalization the same for the[i] filename and classname but i am still having this error message: "error : can't read : filename.java" .
    does that have anything to do with windows xp that i am using or there is absolutely something else that prevents javac from reading and compiling the file?
    please help
    Kind regards
    Nour

    The only 2 reasons that I can figure out why you are getting this error is either because your java file has not been properly named ie. filename.java or else then it is not in the same location ie directory from where you are trying to run your compiler.
    Thus you need to run the compiler from the directory that contains your java source file so it really does'nt matter where you have saved your java file on the machine as long as your path is set to your j2sdk /bin Just cd your way to that directory where you have the java file and run the compiler javac

  • How can we read filenames from a specific folder

    Hi forum,
    I have a situation that, there are several files coming daily in a specific folder.
    I want to read filenames from that folder and want to get that filename in a variable.
    That filename contains account nos. which I need for further processing.
    Now, how can we read filenames from a specific folder with using Oracle PL/SQL Procedure?
    Please suggest.
    Thanks & regards,
    Kiran

    If you are on 10g (not sure which exact release I'm afraid) you might look at Chris Poole's XUTL_FINDFILES that lists the files in a directory using PL/SQL and DBMS_BACKUP_RESTORE.SEARCHFILES (all a bit undocumented as it seems to be provided as part of rman).
    The conventional (i.e. supported) approach is to use a Java stored procedure - there is an example on AskTom.
    Message was edited by:
    William Robertson

  • File-to-File/RFC scenario with reading filename

    Hi,
    i have a File-to-File/RFC scenario which causes some problems in desining it correctly. Maybe some of you has an idea how to do this.
    Scenario:
    - A file is picked up by a File-Adapter. The files are different: pdf, doc, tiff, jpg, txt, ...
    - The file must now go through a business process (not necessary the file, but i need the filename in the business process).
    - The process has to contact several backend systems (SAP R/3) to collect some data. To achieve this the filename has to be send to this systems.
    - The collected data are send via SOAP to a receiver system
    - The file itself has to be stored in a directory via File-Adapter.
    Here's my problem:
    - Is it possible to transport the binary file content within a message which contains other elements (e.g. filename)?
    - Is it possible to do graphical mappings with such a payload (only 1 to 1)? Or must i use Java Mappings only?
    - How to generate a Message from the sender File Adapter which contains binary file content AND filename? Is this possible with a Module?
    - Is it better to create 2 messages with an adapter module? One with the image the other with the filename. Or is it better to split them later in a Mapping?
    Thanks in advance,
    ms

    If all that you need is the file name, use adapter specific settings in the sender file adapter. Then you can access the file name in mapping runtime in UDFs. If you want to have content of the pdf, jpg etc images, i do not think there are ready modules available except for reading pdfs ( you might have to research on this).
    For look ups etc with R3 systems, you can use the file name that you got from the adapter and store it in mapping fields.
    VJ

  • Read filenames of directory

    Hello to all forms developers !
    I have a problem with Forms 6i (client/server). I want the user to select multiple files from a directory. I know this can be done using the OpenFileEx function of the d2kwutil library. But this function only returns a string which max. length is 4096 characters. This restricts the number of selectable files. So I tried another way : I used the HOST built-in to generate a file containing all filenames, like this :
    host('dir /b > files.txt', no_screen) and then read out the filenames with routines of text_io package.
    The parameter /b for the dir command lists only the filenames.
    But to my surprise filenames longer than 8 characters are shortened to only 8 characters so that these filenames cannot be used by other routines.
    Did anyone else face and solve this problem and share his experience with me ?
    Regards
    Kai

    if you have d2kwutil library you can use :
    win_api_directory_list.FirstFile and win_api_directory_list.NextFile functions. Something like :
    WHEN-BUTTON-PRESSED Trigger :
    declare
         hSearch PLS_INTEGER;
         vcFile VARCHAR2(60);
         bIsDir BOOLEAN;
         vcLDir VARCHAR2(1);
         vcRDir VARCHAR2(1);
    begin
         hSearch := win_api_directory_list.FirstFile(:directory_list.directory, vcFile, bIsDir, toBoolean(:directory_list.exceptions));
         :directory_list.result := IsDir(vcFile, bIsDir);
         LOOP
              win_api_directory_list.NextFile(hSearch, vcFile, bIsDir, toBoolean(:directory_list.exceptions));
              EXIT when vcFile is null;
              :directory_list.result := :directory_list.result||chr(10)||IsDir(vcFile, bIsDir);
         end LOOP;
         win_api_directory_list.CloseSearch(hSearch);
    end;
    :directory_list.directory is item which contain folder which you want to list. You can choose folder with function:
    begin
    :directory_list.directory := get_file_name(:directory_list.directory,NULL,NULL,'Select a Folder to list',OPEN_FILE,FALSE)||'\*.*';
    end;
    Item :directory_list.result is result item where it will be stored all file names which exist in folder (instead of this you can create e.g PL/SQL table which will handle all files which is listed in folder.

  • Reading Filename of a attachment

    Hi everyone,
    in the QM03 Transaction I can place some file attachments to the Object. In the attachment window are the attachments listed and with a doubleclick the documents will be opened.  So far so good.
    I can read some informations about the attachments with the   CALL METHOD cl_binary_relation=>read_links and with the 'SWL_GET_OBJECT_INFORMATION'
    function I can read some Information's about the attachments to the object, but not the filename of the attachment.
    How can I get the filename of the attachment?
    Thx in advance.
    Regards Ralf.

    these methods sounds good,the question is,  which value have  these parameters.
    (Classname,client, object_key).
    CALL METHOD cl_bds_document_set=>get_info
      EXPORTING
       logical_system      =
    <b>   classname           =
        classtype           =</b>
       client              =
    <b>*    object_key          =</b>
       check_state         = ' '
    IMPORTING
       connections         =
       extended_components =
    CHANGING
       components          =
       signature           =
    EXCEPTIONS
       nothing_found       = 1
       error_kpro          = 2
       internal_error      = 3
       parameter_error     = 4
       not_authorized      = 5
       not_allowed         = 6
       others

  • Fail read filename from attachment in multipart message

    Hi,
    I use Javamail 1.4 for reading mail from imap server.
    Sometimes i have received mail with this header (this mail was produced with thunderbird):
    --------------040307090809070400040607
    Content-Type: application/pdf;
    name*0="20060908 - DOCUMENT.pdf"
    Content-Transfer-Encoding: base64
    Content-Disposition: inline;
    filename*0="20060908 - DOCUMENT.pdf"
    When i use the method part.getFileName() the result is null.
    Why?
    Thanks all.

    Interesting. What version of Thunderbird?
    These headers are using a feature of RFC 2231 that allows
    a parameter in a header to be split over multiple lines.
    In this particular case, there's no need to use this feature
    since clearly these parameters are short enough to fit on
    one line.
    While JavaMail supports part of RFC 2231 - the part that
    allows parameters to be encoded - it doesn't support this
    aspect of RFC 2231.
    I would suggest reporting this as a "bug" in Thunderbird, that
    it's gratuitously using this new feature in cases where it's not
    needed, and thus reducing interoperability with other mailers
    that don't support this feature.

  • Read filenames from jar-file

    Hi,
    I want to read image names in a jar-file directory in a web start application. This used to work in previous versions of jdk,
    but when I use jdk 1.6.0_20 I get this errormessage:
    "http:\server:8080\test\client.jar The filename, directory name, or volume label syntax is incorrect".
    Why doesn´t this work anymore?
    Some of my code looks like this:
         getFiles("images/toolbuttons/val/", ".gif", true);
         public String[] getFiles(String catalog, String fileNameEnd,
             boolean removePath)
              JarFileFinder jarFileFinder = new JarFileFinder();
              String jarFilePath = jarFileFinder.getClassLocation(
                  this.getClass().getName());
              String[] files = null;
              try
                   if (fileNameEnd != null)
                        fileNameEndFilter = new FileNameEndFilter(fileNameEnd);
                   files = getFilesInJar(jarFilePath, fileNameEndFilter, catalog,
                       removePath);
              catch (Exception e)
                   MessageUtil.messageOk(null, this.getClass().getName(), e.getMessage());
              return files;
         private String[] getFilesInJar(String jarFilePath, FilenameFilter filter,
             String catalog, boolean removePath)
             throws Exception
              ZipFile zipFile = new ZipFile(jarFilePath);
              Enumeration e = zipFile.entries();
              String name;
              ZipEntry zipEntry;
              ArrayList filesList = new ArrayList();
              while (e.hasMoreElements())
                   zipEntry = (ZipEntry) e.nextElement();
                   name = zipEntry.getName();
                   if ((filter == null || !filter.accept(null, name)) ||
                       (catalog != null && !name.startsWith(catalog)))
                        continue;
                   if (removePath == true)
                        name = name.substring(name.lastIndexOf("/") + 1);
                   filesList.add(name);
              String[] files = new String[filesList.size()];
              for (int i = 0; i < filesList.size(); i++)
                   String s = (String) filesList.get(i);
                   files[i] = s;
              return files;
    public class JarFileFinder
         public String getClassLocation(String classname)
              try
                   Class clazz = Class.forName(classname);
                   if (clazz == null) return null;
                   URL url =
                       clazz.getProtectionDomain().getCodeSource().getLocation();
                   String location = url.toString();
                   if (location.startsWith("jar"))
                        url = ((JarURLConnection)
                            url.openConnection()).getJarFileURL();
                        location = url.toString();
                   if (location.startsWith("file"))
                        return new File(URLDecoder.decode(url.getFile(), "UTF-8")).getAbsolutePath();
                   else
                        return URLDecoder.decode(url.toString(), "UTF-8");
              catch (Exception e)
                   MessageUtil.messageOk(null, this.getClass().getName(), e.getMessage());
              return null;
    }

    AndrewThompson64 wrote:
    Lisa_R wrote:
    ..I tried to remove the URLDecoder, but the result was the same. I still get:
    "http:\server:8080\test\client.jar The filename, directory name, or volume label syntax is incorrect".Given an URL should use '/' as opposed to '\', and starts with 2 '/' rather than one, it is not surprising that URL was rejected. Strange as it may seem, programming by typing random characters into an editor will rarely, if ever, work to create a working application.Yes, I agre that it´s not that surprising that the URL was rejected (even though the URL work in firefox and IE). But I didn´t write it that way. The code that put the URL together worked fine in previous versions of the jdk.
    >
    ..The reason why I want to read the filenames from the jar instead of including a list of the names is that if you
    want to add an image then all you have to do is include it in the directory.. That is largely irrelevant, since the Jar needs to be freshly built, uploaded by the developer, and downloaded by the client. Since all of that needs to be done for the addition of a single image, you might as well add an Ant task to the build that provides a single file (like I suggested earlier) that lists the resources of interest. It would take less time to write an Ant task, than debug all the hoops the code is currently jumping through(1) in order to get the information of interest.
    If this was the only place were this method was used I would agre with you, but unfortunatelly it´s not. The application dosen´t only read image filenames it also reads class-names.
    1) And even if you got that working, it would be likely that Sun would introduce some change in the next version of Java that breaks it again. My advice is to stop fighting it, and go with the flow.Thats not good of course! But it has been working for a long time, so I think I will try to make it work again....
    Is there someone out there who has done this or knows how to do it I would appreciate some help! :-)

  • Read FileNames in Directory

    Hi,
    I have to read list of filenames in a directory(defined in topology) into a oracle table
    like
    filnames
    test.csv
    two.csv
    I know how to use procedure sure which is correct approach
    Please help
    Thanks

    Has anyone had any luck getting this to work?
    Is this OS Specific - For instance, Unix or Windows. I am trying to run this on a Windows PC.
    I am receiving an invalid syntax error. The set up I am using below.
    Command on Target =
    import java.lang as lang
    import java.sql as sql
    import snpsftp
    import java.lang.String
    import java.io.File as File
    import ftplib
    import re
    import os
    #db connection
    driverSrc ='<%=odiRef.getInfo("SRC_JAVA_DRIVER")%>'
    lang.Class.forName(driverSrc)
    urlSrc ='<%=odiRef.getInfo("SRC_JAVA_URL")%>'
    userSrc = '<%=odiRef.getInfo("SRC_USER_NAME")%>'
    passwdSrc = '<%=odiRef.getInfo("SRC_PASS")%>'
    ConSrc = sql.DriverManager.getConnection(urlSrc, userSrc, passwdSrc);
    readDBLink = ConSrc.createStatement()
    try:
    # f=open('C:/new.txt','w+')
    list = os.listdir('C:/')
    for fichier in list:
    # str = java.lang.String(fichier)
    # f.write(fichier)
    sqlDBLink = "insert into etl_user.hsd_usage_filenames (FILENAME_ID, FILENAME, CONSUMED) values (ROWNUM, '" + fichier + "', 0)"
    rqteDBLink = readDBLink.execute(sqlDBLink)
    finally:
    ConSrc.close()
    # f.close()
    =====================
    Error received = SyntaxError: ('invalid syntax', ('<string>', 23, 1, "list = os.listdir('C:/')"))
    Any assistance that can be offered is greatly appreciated.
    Thanks,
    Via
    Edited by: via_odi on Nov 1, 2012 12:49 PM

  • Compilation error - cannot read filename

    Hello,
    I am just a starter in Java. I have installed the standard Development kit j2sdk1.4.1_01 on a Windows NT machine. The installation went well.
    When I tried compiling my first file HelloWorldApp.java which is in a directory java, it gave the error 'cannot read: HelloWorldApp.java',
    I have set the path command correctly and typed the following command:
    C:>Java>javac HelloWorldApp.java on the command prompt.
    It is giving same error for other files also, can anyone tell me what is the problem?
    Thanks,
    Sunil

    The error comes from the javac compiler when it can not find the file that you specified. In your case, it is saying that it can not find a file named HelloWorldApp.java in the c:\java directory.
    It is common for this error to be caused by the editor you used to create the file, if the editor is like Notepad. Notepad will append .txt to the file name. If you use the dir command from c:\java you should see HelloWorldApp.java, not HelloWorldApp.java.txt. If that is the problem, a quick work around is to put double quotes around the file name when you save it to keep Notepad from adding .txt.
    http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

  • How to read 16 bits at a time from a file.

    Hi everyone:
    I have a homework problem that requires me to read from a file 16 bits at a time, which is a signed value. I have tried using the code below:
    try     {
         FileInputStream fis = new FileInputStream(fileName);
         DataInputStream dis = new DataInputStream(fis);
         System.out.println("Reading "+fileName+"...");
         int x,y;
         bytes = new int [];
         for(y=0;y<height;y++)      {
              bytes[y] = dis.readByte();
              dis.close();
              fis.close();
              System.out.println("Read "+fileName+" Successfully.");
         } // try
         catch(Exception e)      {
              System.err.println(e.getMessage());
              System.exit(1);
    But this code only reads a byte at a time, I need to read 16 bits at a time. Does anyone have any ideas?
    Any help is greatly appreciated.
    Celia

    DataInputStream has another method that does what you want.

Maybe you are looking for

  • How to enforce index in oracle query

    Hi all how to enforce index in oracle query Regards

  • Create or Replace Package syntax different in SQL Navigator?

    Hi, I compared the same piece of code in both toad and sql navigator. In toad, the syntax for Package was as follows: CREATE OR REPLACE package body name_of_package but in SQL Navigator, the same code is displayed as follows: package body name_of_pac

  • Does anyone know anything about EchoLink?

    I am using an iMac with wireless Airport, which my husband also uses on his XP. He would like to hook up to EchoLink. The information says: Allow UDP(source port any, destination ports 5198-5199)from Internet to PC Allow UDP(source port any, destinat

  • Installing Rosetta from a script

    Hi, I need to be able to install the rosetta component in Snow Leopard from a script file. We have a management tool that allows us to run scripts on our macbooks. We need to install a new piece of software across the company and this software requir

  • IOS7: Images for Wallpaper Are Cropped

    I have just updated my iPhone 5 to iOS 7 and am trying to use a picture of a painting as a wallpaper. However, the OS scales it up in the Wallpaper menu such that it crops it approximately 20% all around. I can zoom it in further but I cannot zoom it