Iterrate through an array of files

I am having trouble with the following program, making to iterate through an array of three files, that
are placed in a directory below the program directory. What I would like my program to do is to read 10 lines of each of the files in the subdirectory and then go back and read another 10 lines from the each files(remembering which file is which) and so on till all the files are read. The number of the files in the subdirectory can change, therefore nothing should be hardcoded!
Here is the program so far:
public class thekernel {
public void thekernel() {}
public void executeKernel() throws Exception {
boolean read = false;
String input_line = null;
int quantum = 10;
int programCounter = 0;
String dirname = "processdir";
File f1 = new File(dirname);
if (f1.isDirectory()){
String s[] = f1.list();
for(int i = 0; i < s.length; i++) {
System.out.println (s);
while ( i < s.length ) {
RandomAccessFile fr =
new RandomAccessFile (("processdir/")+s[i], "r");
while (((input_line=fr.readLine()) != null) &&
( programCounter < quantum )){
System.out.println (input_line);
programCounter++;
i++;
programCounter = 0;
public static void main(String args[]) throws Exception {
thekernel K = new thekernel();
K.executeKernel();
here is the output it produces at the moment:
Process_1.txt
1FORK 1F1
FORK 2
WAIT 4
WAIT 2
FORK 5
FORK 6
ABCD 7
FORK 8
FORK 9
ABCD 10
2FORK 1F2
FORK 2
ABCD 3
WAIT 4
FORK 5
FORK 6
ABCD 7
FORK 8
FORK 9
ABCD 10
3FORK 1F3
FORK 2
ABCD 3
WAIT 1
FORK 5
FORK 6
ABCD 7
FORK 8
FORK 9
ABCD 10
Any help much appreciated.........................

You should create an collection of rafs, one for each file, then when you switch between files, the location will be intact.You still need to logic to determine when all of the files have been read. One idea could be to use a vector to hold the rafs, and remove each one as the the eof is reached. When the vector is empty, then all of the files will have been read.
Something like:
public void executeKernel() throws Exception {
    final int QUANTUM = 10;
    String dirname = "processdir";
    File f1 = new File(dirname);
    if (f1.isDirectory()){
        String s[] = f1.list();
    class Foo {
        public String name;
        public RandomAccessFile file;
        public Foo(String name, RandomAccessFile file) {
            this.name = name;
            this.file = file;
    Vector files = new Vector()
    for(int x = 0; x < s.length; x++)
        files.add(new Foo(s[x], new RandomAccessFile (("processdir/")+s[x], "r"))));
    String input_line = null;
    int programCounter = 0;
    while(files.size() > 0) {
        for(int i = 0; i < files.size(); i++) {
            System.out.println ( ((Foo)files.elementAt(i)).name );
            programCounter = 0;
            while (programCounter < quantum ) {
                if( (input_line = ((Foo)files.elementAt(i)).file.readLine()) != null) {
                    System.out.println (input_line);
                    programCounter++;
                else {
                    files.removeElementAt(i);
                    programCounter = quantum;

Similar Messages

  • Stepping through an array

    Dear Forum members,
    Can anyone provide some guidance about how to step through and process data in an array file.  My outline LabVIEW program is to carry out the following steps:
    (1)  Take the first 5 samples from the data file (which contains 1000 samples)
    (2)  Process calculation
    (3)  Take the next 5 samples and process calculation Step (2) until the last batch of samples is reached
    I understand that I will need a loop (200 x 5 samples = 1000 samples analysed), but what I cannot get is how to programmatically step through the array rows, 5 at a time.  If anyone can help it would be appreciated.
    Regards,
    Solved!
    Go to Solution.

    Hi bunnykins,
    Using the Array Subset vi, this becomes a fairly simple problem.
    Just specify a start point and a length of data you want then you can pull a small array of data out of a large one.
    I have attached an example for you to tweak to whatever you need.
    Enjoy!
    -Rob Afton
    Electrical Engineering Intern
    GHSP
    Attachments:
    Subarray Calculations.vi ‏12 KB

  • Looping through an array to pass out the variable to Scanner

    I'm trying to get an array of files which end .list in a particular directory and then scan each one for an email address and at the moment print it out. As I understand it Scanner doesn't read from File but will from a String. However each time I try putting it into a String, I get an error as the code tries to pass the full array to it rather than the file names.
    What would be the best way of looping through the array so that each time Scanner gets a new path name applied to it?
    import java.io.*;
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.regex.*;
    import java.io.File;
    public class FindEmail {
         public static void main(String[] args) throws IOException {
              File userDir = new File("M:\\foo\\bar");
            FileFilter listfilter = new fileFinder();
            File[] foundarray = userDir.listFiles(listfilter);
            for (File i: foundarray) {
              Scanner s = new Scanner(new File(foundarray));
            try {
            Pattern p = Pattern.compile("([\\w+|\\.?]+)\\w+@([\\w+|\\.?]+)\\.(\\w{2,8}\\w?)");
            String str = null;
                 while ( (str = s.findWithinHorizon(p, 0)) != null ){
                     System.out.println(str);
            } finally {
               if (s != null) {
                  s.close();
                }//if
            }//finally
            }//for
         } //main
    }//class
    //class to find the list files
    class fileFinder implements FileFilter {
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".list");
    }

    The error that I got was
    Exception in thread "main" java.io.FileNotFoundException: [M:\foo\MAIN\BEDEWORK.LIST, M:\foo\MAIN\BEDEWORKSPRIVATE.LIST, M:\foo\MAIN\DONNA-NEW.LIST, M:\foo\MAIN\DONNA-NEWER.LIST, M:\foo\MAIN\DONNA-TEST.LIST] (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at org.stfc.bedework.FindEmail.main(FindEmail.java:17)At the time I had the code:
    FileFilter listfilter = new fileFinder();
               File[] foundarray = userDir.listFiles(listfilter);
               String name = Arrays.toString(foundarray);
               for (int i=0; i<name.length(); i++) {
              Scanner s = new Scanner(new File(name));

  • Writing data from array to file

    May i know how to write string from a array into a file.
    I have use string tokenizer to extract every line from a file using readline and use stringtokenizer to spilt the line using tab delimiter for processing.
    But if i want to write data from array to file with tab as a delimiter and how to go to the next line. How do i do that. Below is the task and i have state a simple example on a array i have and the file output that i want.
    Pls advice.. Thanks
    eg of a array
    array[0] = Data
    array[1] = One
    array[2] = Data
    array[3] = Two
    array[4] = Final
    array[5] = Data
    From the above array, i want to write to a file so that it will appear something as below
    Eg textfile.txt
    Data One
    Data Two
    Final Data
    PLs attached a simple code as a example as i am only begining to start useing the IO feature in java. Thanks

    Really thanks for your help,
    but u are mentioning that i have already know the number of countters in advance , that is to say the 2 * counters.
    But is there a way to solve this problem which i mean if i dun know the number of predefined counters. Maybe i should say, there is more than 2 counters and in another situation, the counters will only be defined during runtime. Actually the solution u give will work nicely with 2 counters. but wat if the counter is more than 4, i wll have to concatenate the string a lot of time. so is there any solution around this problem. That why i am wandering if tere is any solution to write to the file when the counters can be only determined in runtime
    Pls advice on the above with a code samples if possible.

  • Looping through javabean array in jsp?

    Hello,
    In my servlet, I created an ArrayList of objects and pass these to a jsp page using:
    req.setAttribute("bean", uploadList);
    The ArrayList contains objects of the FileBean class, with a getIndex, and getDate methods.
    Could any possibly demonstrate how to loop through the ArrayList in the jsp and display the FileBean object values in a html table?
    To display the values of a javabean in jsp pages I normally have to use for example, requestScope.bean.getMethod();
    Thanks

    No, that would be requestScope.bean.attributename, if your getter method has the same name as the attribute you are getting.
    To loop through an array you have to use the c:forEach tag. Check google for "jstl foreach example", there are loads of examples.

  • Extended Analytics - Is it possible to extract data from HFM to MS Access through an UDL (OBDC) file?

    Hello,
    I am trying to extract data from HFM, using Extended Analytics, to MS Access through an UDL (OBDC) file but it displays the following error:
    "error occurred while connecting to the database"
    I've followed these steps:
    1. Create a blank MS Access database (.mdb format)
    2. Create an .UDL file which connects to MS Access database:
          - Provider: Microsoft Jet 4.0 OLE DB Provider
          - Connection: Linked to the .mdb database created in step 1.
          - Give "ReadWrite" permissions.
    3. Test .UDL file connection successfully.
    4. Create DNS with Extended Analytics DNS Configuration tool.
    5. In Extended Analytics (HFM), once selected the new DNS and extract it displays the error commented before.
    ¿Do you know how i can solve this issue?
    Thank you in advance,
    Best regards,

    Hello Anjum Ara,
    Thank you for your response.
    I don't understand how to add my database SID to tnsnames.ora. (I already found the file but i don't know how to add new database SID)
    I have created one MS Access database in "C:\TEST.mdb" and i want to connect Extended Analytics to it.
    How i have to add this database into tnsnames.ora file?
    Thank you in advance,
    Kind regards

  • KP06 mass planning through a single CSV file

    Hi All,
    I have created one Planning layout and assign it to a planner profile for KP06 upload. We are using CSV format file for this upload. Now i am able to upload Kp06 plan data for a single cost center for one period only.
                   But my client is asking for all cost centers plan for all periods through a single CSV file(mass planning). If its not possible for all periods plz guide me how to do for all cost centers for one period.
       it would be appreciated if any one help on this issue.
    Regards,
    Spandana

    Hi Nikolas
    Still - Does Excel upload allows you to upload multiple cost centers at a time??
    To upload by All periods in one go - One needs to define 12 Columns for the Key Figures.... But is multiple cost centers possible?? As far as I remember from SDN posts, its not possible
    @ Spandana - I personally Luv LSMW for the same reason... You can upload all in one go and per sec it uploads avg 6 records in KP06... That speed is decent enuf
    br, Ajay M

  • 3D string array to file

    How can I write a 3D string array to file?

    sascha:
    You could do this a lot of different ways.
    The first and most obvious thing that comes to my mind is that you can
    think about a 3D array as an array of 2D arrays. (For that matter a
    2D array is an array of 1D arrays.)
    Thus you could use a for loop to index your 3D array down to 2D and
    then perform multiple writes to write each 2D array "element" of this
    array of 2D arrays to disk. You would probably want to write some
    sort of header which defines how many dimensions there are in the
    array so that whatever reads it back later will have an easier time
    reading it back. (Otherwise you'd have to implement EOF handling for
    the read back portion.)
    To read it back you just use the same logic but build a 3D array using
    a 2D read inside a for loop.
    Dou
    glas De Clue
    LabVIEW developer (looking for a job...
    [email protected]
    [email protected] (SaschaS) wrote in message news:...
    > How can I write a 3D string array to file?

  • [svn:osmf:] 17548: Remove left-over event handler, which could trigger an unnecessary event if a player loaded plugins through the config XML file and manually  (e.g.

    Revision: 17548
    Revision: 17548
    Author:   [email protected]
    Date:     2010-09-01 14:09:14 -0700 (Wed, 01 Sep 2010)
    Log Message:
    Remove left-over event handler, which could trigger an unnecessary event if a player loaded plugins through the config XML file and manually (e.g. for static plugins).
    Modified Paths:
        osmf/trunk/libs/samples/ChromeLibrary/org/osmf/chrome/configuration/PluginsParser.as

    Remember that Arch Arm is a different distribution, but we try to bend the rules and provide limited support for them.  This may or may not be unique to Arch Arm, so you might try asking on their forums as well.

  • Searching through an array of objects

    Hi, I am currently working on an assignment where I have to create a class called Persons with data fields of Name(String),age(int),income(int).
    All the values including the string values for name and values for income and age are all randomly generated and are stored in an array of objects of class "Persons".
    The array size is user specified.
    What I must attempt to implement now is to make a search feature that lets the user search through the array of objects for a particular name.
    I'm having some bad luck trying to implement this feature.
    If anyone can help me, I would greatly appreciate that!
    Cheers.

    Hi, Thank you for the prompt reply.
    I do not yet know HOW to start this,I mean I know how to search for individual characters in an element of an array, but to search for whole strings I am quite unsure.
    public class Persons
        //data fields
        private String name;
        private int age;
        private int income;
        //Constructor for Class Persons
        public Person(String[] name,int[] age,int[] income)
              String[] tempName = name;
              int[] tempAge = age;
              int[] itempIncome = income;
        //Instance method for returning some basic values about personal data
        public void toString(Persons ofChoice)
            System.out.println("Persons Data");
            System.out.println("Name: " + ofIntrest.name);
            System.out.println("Age: " + ofIntrest.age);
            System.out.println("Income: $" + ofIntrest.income);
    }This is my Persons class code, but I am quite stumped how to search for whole strings at the time being.

  • Create Class objects from an Array of File Objects

    Hi There,
    I'm having extreme difficulty in trying to convert an array of file objects to Class objects. My problem is as follows: I'm using Jfilechooser to select a directory and get an array of files of which are all .class files. I want to create Class objects from these .class files. Therefore, i can extract all the constructor, method and field information. I eventually want this class information to display in a JTree. Very similar to the explorer used in Netbeans. I've already created some code below, but it seems to be throwing a NoSuchMethodError exception. Can anyone please help??
    Thanks in advance,
    Vikash
    /* the following is the class im using */
    class FileClassLoader extends ClassLoader {
    private File file;
    public FileClassLoader (File ff) {
    this.file = ff;
    protected synchronized Class loadClass() throws ClassNotFoundException {
    Class c = null;
    try {
    // Get size of class file
    int size = (int)file.length();
    // Reserve space to read
    byte buff[] = new byte[size];
    // Get stream to read from
    FileInputStream fis = new FileInputStream(file);
    DataInputStream dis = new DataInputStream (fis);
    // Read in data
    dis.readFully (buff);
    // close stream
    dis.close();
    // get class name and remove ".class"
    String classname = null;
    String filename = file.getName();
    int i = filename.lastIndexOf('.');
    if(i>0 && i<filename.length()-1) {
    classname = filename.substring(0,i);
    // create class object from bytes
    c = defineClass (classname, buff, 0, buff.length);
    resolveClass (c);
    } catch (java.io.IOException e) {
    e.printStackTrace();
    return c;
    } // end of method loadClass
    } // end of class FileClassLoader
    /* The above class is used in the following button action in my gui */
    /* At the moment im trying to output the data to standard output */
    private void SelectPackage_but2ActionPerformed(java.awt.event.ActionEvent evt) {
    final JFileChooser f = new JFileChooser();
    f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int rVal = f.showOpenDialog(Remedy.this);
    // selects directory
    File dir = f.getSelectedFile();
    // gets a list of files within the directory
    File[] allfiles = dir.listFiles();
    // for loop to filter out all the .class files
    for (int k=0; k < allfiles.length; k++) {
    if (allfiles[k].getName().endsWith(".class")) {
    try {
    System.out.println("File name: " + allfiles[k].getName()); // used for debugging
    FileClassLoader loader = new FileClassLoader(allfiles[k]);
    Class cl = loader.loadClass();
    //Class cl = null;
    Class[] interfaces = cl.getInterfaces();
    java.lang.reflect.Method[] methods = cl.getDeclaredMethods();
    java.lang.reflect.Field[] fields = cl.getDeclaredFields();
    System.out.println("Class Name: " + cl.getName());
    //print out methods
    for (int m=0; m < methods.length; m++) {
    System.out.println("Method: " + methods[m].getName());
    // print out fields
    for (int fld=0; fld < fields.length; fld++) {
    System.out.println("Field: " + fields[fld].getName());
    } catch (Exception e) {
    e.printStackTrace();
    } // end of if loop
    } // end of for loop
    packageName2.setText(dir.getPath());
    }

    It's throwing the exeption on the line:
    FileClassLoader loader = new FileClassLoader(allfiles[k]);
    I'm sure its something to do with the extended class i've created. but i cant seem to figure it out..
    Thanks if you can figure it out

  • Shifting through an array

    I am trying to iterate through an array using a set of coordinates, when the number's of the coordinate is positive the x&#8217;coord moves right and the y&#8217;coords moves left. When the number's of the coordinate is negative it moves in the opposite direction.
    So if x &#8216;coord is 4 it will move 4 element to the right
    and if x &#8216;coord is -4 it will move 4 element to the left
    Therefore in some cases I will need to move from the end of the array to the beginning.
    I will be really grateful for any help offered. Thank you.

    Therefore in some cases I will need to move from the
    end of the array to the beginning.I think the post is pretty vague, but it seems the above is the key. You want a "circular" array? After adding/subtracting from the index, compare the result with the length of the array. If the result is < 0, add array.length to it. If it is >= array.length, subtract array.length from it.
    So, for example, if your array is 10 long (indexes 0 thru 9), and you are currently at index 7 (the 8th element), and you "move" by +5, 7 + 5 = 12, which is outside the array boundaries, so you subtract 10, giving the final new index = 2 (or the 3rd element). Clear as mud?

  • How to add array of file types to file dialog box

    Hi
    I just want to know how to add array of file types in file dialog box vi. I know that multiple file type can be added to filedialog vi in the pattern Input string separated by semicolon (eg *.vi;*.doc;*.jpeg;*.xls). But i want file dialog which is shown in the below picture.
    I think that file dialog vi call user32.dll but i don't have that header file to call that dll.
    Waiting for your esteemed response.
    Thanks & Regards
    Samuel J
    System Engineer
    Captronic Systems Pvt Ltd
    Bangalore, India.

    I'm not sure how (or even if) it can be achieved using the LabVIEW built-in open dialog, but a .NET call to openfiledialog (http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx) can do what you're looking for. The .NET functions are better documentented that simple user.dll calls, so it might be easier to implement.
    Shaun

  • Currency changes rates through TBEX from excel file getting erro

    Hi,
    When i am trying to upload the currency changes rates through TBEX from excel file getting error message:
    Error "The macro 'ThisWorkbook.TableBackToR3' cannot be f" occurred during macro execution
    Kindly guide what macro i need to define in excel sheet. or should i need to activate something in excel sheet relates to macros.
    Regards,
    Salil...

    When you call it the first time, it new Shell() constructs a new Display for you (the default).
    The second time, it gets the default display, but you are in a different Thread now. Since you have to create your widgets in the UI thread, it gives you that error.
    To run code in the UI thread, Display provides two methods:
    display.syncexec(..)and
    display.asyncexec(...)see
    http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/swt_threading.htm
    for more details.

  • Array of files

    Hi!
    I'm creating simple image viewer and i'd like to add 2 buttons (got biiig problems with that too so now i'm trying with keyboard:) for moving to next or previous image in directory, starting from the image which is actually loaded.
    How to do that?

    Thanks for answering.
    What do you mean by "data model"? I'm really new to java...
    All loading, saving and displaying images already works.
    I've found listFiles function and i'm using it with a image file filter like this
    File[] files = file.listFiles((FileFilter)filter);
    but how to is this list created? Is the loaded file the first one in this array or is it created alphabetically? The more complicated my application is the less my debugger works :) so i can't check it by myself. Do i have to search the array for my file, store its index and then use it to move back and forward? If yes, how to search array of files for specific file?

Maybe you are looking for