Reading file line by line in reverse order

hi,
can anybody tell me that how can I read a txt or csv file line by line in reverse order?
thanks in advance.

Please don't cross post - http://forum.java.sun.com/thread.jspa?threadID=5283758&messageID=10193925#10193925

Similar Messages

  • Read file line by line

    Hi
    Could somebody tell me how to read file line by line ? Namely my input file I want to read look as follow:
    AAA 1, 1
    12 222 12
    AAA 2, 2
    11 122 11
    My output file should look as follow:
    1, 1, 12
    1, 1 222
    1, 1, 12
    2, 2, 11
    2, 2, 122
    2, 2, 11
    I think the lines need to be stored in ArrayList, then I would like those lines to write to csv file, but how on read I can construct such output file? This is my code for reading file
    public ArrayList readFile(String filename)
      try
         BufferedReader in = new BufferedReader(new FileReader(filename));
         ArrayList list = new ArrayList();
         String lineS = null;
         while (in.ready())
          if ((lineS = in.readLine()).startsWith("")){
            String[] line = in.readLine().trim().split("\\s+");
            list.add(Integer.valueOf(line[0]));
            list.add(Integer.valueOf(line[1]));
            list.add(Integer.valueOf(line[2]));
         in.close();
         return list;
         catch (Exception e)
       e.printStackTrace();
    return null;
    Thanks

    The rules for the conversion from input to the desired output are:
    1. For each of the line with string take 2 integers for example 1, 1  from AAA 1, 1
    2. Then repeat 1, 1 for each next number not containing any string, so if the line after AAA, 1, 1 has 12, 222, 12 then the output will look as follow
    1, 1, 12
    1, 1 222
    1, 1, 12
    3. Repeat the process (the pattern is the same 1 line with string 1 line with numbers)
    Actually I am not sure how to perform that logic for such conversion as for now I am only able to list only the numbers but I have a problem to add numbers from the line having string in it.
    STOP!
    You should NOT be writing code if you are 'not sure how to perform that logic'.
    You are getting ahead of yourself.
    There is NOTHING to gain by trying to code a solution before you know what algorothm you need. Big mistake.
    Should I use list or maybe if the patter for lines is the same array will be more sufficient?
    NEITHER ONE!
    Those are 'solutions' used to implelment an algorothm.
    You do NOT yet know what algorithm you need to use so how can you possibly write code to implement the unknown?
    How to perform logic to get the numbers from line having string and for the next lines having only numbers in order to structure it into desired output? 
    THAT is the question your thread subject should have.
    Until you get the answer to it don't write any code,.
    Do NOT try to automate what you can't do manually.
    Write down, on paper or use an editor, the step by step 'logic' you need and walk through that logic from beginning to end until the 'logic' works and produces the correct result.
    You just now have started to do that when you listed those rules above.
    But you left some things out. Expand on that list of 'rules' and provide a little more example data. TPD has given you a good example. Reread what they said.
    Did you notice they start by talking about 'tasks': what each task does and the order the tasks need to be performed.
    That 'task list' has NOTHING to do with Java, C, or any other language: it is identifying the problem/algorithm. Until you have that coding is premature.

  • Reading file line by line

    I want to read an input file line by line and tokenize only certain lines of the file.
    For example, I want to read in a file, go to the fourth line, tokenize it,and print the 4th and 7th token to an output file.
    Then skip two lines and tokenize the next line, and print the last token to the same output file.
    I want to keep doing this until I reach the end of the file. How can I specify that I want to go to the 4th line, skip two lines, skip two lines again, etc
    Here is my attempt:
    public class Practicing
    public static void main (String [] args)
    try
    //open output stream
    OutputStream fout= new FileOutputStream(Input.readString("Output Filename:"));
    OutputStream bout= new BufferedOutputStream(fout);
    OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");
    //open input stream
    File inputFile = new File(Input.readString("Input Filename:"));
    InputStream inStream = new FileInputStream(inputFile);
    InputStreamReader inreader = new InputStreamReader(inStream, "8859_1");
    BufferedReader reader = new BufferedReader(inreader);
    String line = reader.readLine();
    int index = 0;
    StringTokenizer st;
    while((line !=null))
          st = new StringTokenizer(line, " ");
    // get the number of tokens and create an Array of that many elements
            int numTokens = st.countTokens();
            String[] strArray = new String[numTokens];
    // assign each token to a 'slot' in the Array
            for (int i = 0; i < numTokens; i++) {
                strArray[i] = st.nextToken();
          System.out.println(strArray.length); // prints array length to out
          //for (int i = 0; i < strArray.length; i++) {
             // System.out.println(strArray);
    out.write(strArray[4] + "&" + strArray[7] + "&");
         line = reader.readLine();
    out.flush();
    out.close();
    catch(IOException e)
    System.out.println("IOException caught");
    System.out.println(e.getMessage());
    Thanks

    String line = "";
    int index = 0,
        counter = 0;  // For counting lines
    StringTokenizer st;
    int[] linesToTokenize = int[] {4,6,999};
    while(( line = reader.readLine() ) !=null)
      counter++;
      st = new StringTokenizer(line, " ");
      for (int i = 0; i < linesToTokenize.length; i++)
        if ( counter == linesToTokenize[i] )  // keeps track of line#
    // get the number of tokens and create an Array of that many elements
            int numTokens = st.countTokens();
            String[] strArray = new String[numTokens];
    // assign each token to a 'slot' in the Array
            for (int i = 0; i < numTokens; i++) {
                strArray[i] = st.nextToken();
          System.out.println(strArray.length); // prints array length to out
          //for (int i = 0; i < strArray.length; i++) {
             // System.out.println(strArray);
    out.write(strArray[4] + "&" + strArray[7] + "&");

  • Reading File line by line and storing in a collection?

    I'm trying to figure out how I can read a file that has a bunch of internet address.
    For example:
    www.google.com
    www.blah.com
    www.hardyharhar.com
    I would like to store them either in a hashtable or a vector so I could use the address in my program. Could someone tell me the best approach to go about doing this ? Should I be using the FileInputStream or what?
    Thanks

    Need a little help with how to use the bufferedreader with the FileInputStream. This is what I have so far:
    import java.io.*;
    public class ReadFile {
      private static File file;
      private static FileInputStream fis;
      private static BufferedReader bdr = null;
      private static String record = null;
      private static String str[] = new String[100];
      public static void main(String[] args) {
        try {
         displayAddress("hosts.txt");
        } catch(IOException ex) {
          log("IOException in main");
      public static void displayAddress(String fileName) throws IOException {
        try {
          FileInputStream fis = new FileInputStream(fileName);
        } catch(FileNotFoundException ex) {
          log("File Not Found");
          bdr = new BufferedReader(new InputStreamReader(fis));
          for(int i = 0; i < 100; i++) {
            if(str.equals("[stop]")) break;
    System.out.println(str[i]);
    public static void log(String msg) {
    System.out.println(msg + "\n");
    The file i'm using looks like the one above:
    www.google.com
    www.blahblah.com
    www.hardyharhar.com
    [stop]
    I seem to be getting a null pointer exception(my personal favorite) near the for loop. My educated guess for why is that I don't have a 100 names in the file I'm trying to read. But not sure could someone tell me how I can fix this? For right now i'm just trying to print them one by one to the output.

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • Reverse order in File- Open dialogue

    The file/folder list in the File->Open dialogue window is "stuck" at showing in reverse order. I can right-click in the Open dialogue window and sort ascending, but the next time I open a file it is back to reverse order.
    I have experimented with Explorer's view settings but Reader appears to ignore those. Other applications, for example Word, use Explorer's view settings and behave as I would expect.
    I suspect that someone has inadvertently changed something on this PC. Perhaps there's a keystroke combination that changes the file display order persistently?
    Any ideas, please?
    Adobe Reader version 8.1.2
    XP Pro SP2

    I'm still struggling with this - does anyone know how to change the file sort order in the File->Open dialogue?
    It must be possible to change it because it has somehow been changed to reverse order!

  • Rename files in reverse order

    Hi all,
    I'm looking for a script that can rename "n" files inside a folder in reverse order (preserving extension):
    OLD NAME --> NEWNAME
    file1.ext --> file(n).ext
    file2.ext --> file(n-1).ext
    file3.ext --> file (n-2).ext
    file(n) --> file 1
    Is there something available online to do that with Apple Script? I've tried almost al "renamer tools" available but none can do such a thing and I'm not able to script something so this is why I'm asking here
    TIA

    The following script should do what you are asking for, although it is rather slow with folders containing a large number of files. There most likely exist much faster solutions. I hope this one can help anyway. Run the script from the AppleScript Editor.
    *set theFolder to choose folder*
    *tell application "Finder"*
    *   set theFiles to files of theFolder as alias list*
    *   set N to (count theFiles)*
    *   set N2 to 2* * *N + 1*
    *   repeat with thisFile in theFiles*
    *      set {theName, theExtension} to {name, name extension} of thisFile*
    *      set {theName, theNumber} to my rename(theName, theExtension)*
    *      set name of thisFile to theName & (N2 - theNumber) & "." & theExtension*
    *   end repeat*
    *   set theFiles to files of theFolder as alias list*
    *   repeat with thisFile in theFiles*
    *      set {theName, theExtension} to {name, name extension} of thisFile*
    *      set {theName, theNumber} to my rename(theName, theExtension)*
    *      set name of thisFile to theName & (theNumber - N) & "." & theExtension*
    *   end repeat*
    *   set theFolderName to name of theFolder*
    *end tell*
    *tell me to activate*
    *beep 2*
    *display dialog "The " & N & " files of folder “" & theFolderName & "” have been renamed in reverse order." buttons {"OK"} default button 1 with icon 1*
    *on rename(theName, theExtension)*
    *   set L1 to (offset of "." & theExtension in theName) - 1*
    *   set theName to text 1 through L1 of theName*
    *   set theDigits to {}*
    *   repeat with k from 1 to L1*
    *      set thisDigit to item -k of theName*
    *      if thisDigit is in "1234567890" then*
    *         copy thisDigit to the end of theDigits*
          else
    *         exit repeat*
    *      end if*
    *   end repeat*
    *   set theNumber to (reverse of theDigits) as text*
    *   set L2 to length of theNumber*
    *   if L1 = L2 then*
    *      set theName to ""*
       else
    *      set theName to text 1 through (L1 - L2) of theName*
    *   end if*
    *   return {theName, theNumber}*
    *end rename*

  • Arraylist only reading first line of file

    I am reading a text file using an arraylist. my file has a single value on each line e.g.
    2
    3
    4
    5
    however this method is only reading only the first line of each file. is it because of this statement:
    String s1[] = number.split("\\s");
    I would like to change the method so its not expecting numbers in a single line.. but reads each line and adds it to the collection... how can I do that?
    here is getData method that gets the file and processes it.
         public static List<Integer> getData(String Filename) {
              List<Integer> array1 = null;
              // BufferedReader for file reverse.txt
              try {
                   array1 = new ArrayList<Integer>();
                   BufferedReader bf = new BufferedReader(new FileReader(Filename));
                   String number = bf.readLine();
                   String s1[] = number.split("\\s");
                   for (int i = 0; i < s1.length; i++)
                        array1.add(Integer.parseInt(s1));
              } catch (Exception e) {
                   e.printStackTrace();
              return array1;

    Faissal wrote:
    while(bf .ready()){
    readline() will return null if the end of the stream has been reached. ([http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html]). This condition can be used to determine when to stop reading thereby ensuring that all lines have been read.
    EDIT:
    Here's a code snippet from [Java Developers Almanac|http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html]: notice how they close() the stream when they're finished with it.

  • Reading specific lines in a file

    hI
    i need to write a program which has a file name a.txt the contents in the file is
    SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND D.MENUGROUP = :1** AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND C.OPRID = :2** ORDER BY D.MENUORDER, D.MENUNAME
    Bind-1 length=21 value=&Administer Workforce
    Bind-2 length=6 value=NLWAJP
    I need to read the file in such a way that in the SQL statement in the place of ":1" I need to get Bind-1 value i.e., &Administer Workforce and same with :2 I need to get Bind 2 value NLWAJP
    Output must be like this
    SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND D.MENUGROUP = &Adminster Workforce AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND C.OPRID = NLWAJP ORDER BY D.MENUORDER, D.MENUNAME

    thomas.behr wrote:
    Read in your text file line by line, then replace \*XXX\*:Y** with the appropriate value using regular expressions.
    Phani532 wrote:The above answers doesnot answer my question....
    I am putting my question in refined format...Wrong. import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Test {
      private static final String DEFAULT_TEXT =
      "SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND *D.MENUGROUP = *:1** AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND *C.OPRID = *:2** ORDER BY D.MENUORDER, D.MENUNAME\n" +
      "Bind-1 length=21 value=&Administer Workforce\n" +
      "Bind-2 length=6 value=NLWAJP";
      public static void main( String[] args ) {
        final List<String> lines = new ArrayList<String>();
        try {
          BufferedReader br = null;
          try {
            br = new BufferedReader(new StringReader(DEFAULT_TEXT));
            String line;
            while ((line = br.readLine()) != null) {
              lines.add(line);
          } finally {
            if (br != null) {
              br.close();
        } catch (IOException ioe) {
          lines.clear();
          ioe.printStackTrace();
        if (!lines.isEmpty()) {
          Collections.sort(lines, new Comparator<String>() {
            public int compare( final String s1, final String s2 ) {
              if (s1.startsWith("Bind-")) {
                if (s2.startsWith("Bind-")) {
                  return s1.compareTo(s2);
                } else {
                  return -1;
              } else {
                if (s2.startsWith("Bind-")) {
                  return 1;
                } else {
                  return s1.compareTo(s2);
          final Map<String, String> parameters = new HashMap<String, String>();
          for (String line : lines) {
            if (line.startsWith("Bind-")) {
              parameters.put(line.substring(5, line.indexOf(' ')), line.substring(line.indexOf("value=") + 6));
            } else if (line.startsWith("SELECT ")) {
              final Matcher matcher = Pattern.compile("\\*(.*?)\\*:([\\d]*?)\\*\\*").matcher(line);
              final StringBuilder sb = new StringBuilder();
              int last = 0;
              while (matcher.find()) {
                final int idx = matcher.start();
                if (idx > last) {
                  sb.append(line.substring(last, idx));
                sb.append(matcher.group(1));
                sb.append(parameters.get(matcher.group(2)));
                last = matcher.end();
              if (last < line.length()) {
                sb.append(line.substring(last));
              System.out.println(sb.toString());
    }(Lucky you, I'm feeling generous - and eager to code.)

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • How can I input read a line from a file and output it into the screen?

    How can I input read a line from a file and output it into the screen?
    If I have a file contains html code and I only want the URL, for example, www24.brinkster.com how can I read that into the buffer and write the output into the screen that using Java?
    Any help will be appreciate!
    ======START FILE default.html ========
    <html>
    <body>
    <br><br>
    <center>
    <font size=4 face=arial color=#336699>
    <b>Welcome to a DerekTran's Website!</b><br>
    Underconstructions.... <br>
    </font> </center>
    <font size=3 face=arial color=black> <br>
    Hello,<br>
    <br>
    I've been using the PWS to run the website on NT workstation 4.0. It was working
    fine. <br>
    The URL should be as below: <br>
    http://127.0.0.1/index.htm or http://localhost/index.htm
    <p>And suddently, it stops working, it can't find the connection. I tried to figure
    out what's going on, but still <font color="#FF0000">NO CLUES</font>. Does anyone
    know what's going on? Please see the link for more.... I believe that I setup
    everything correctly and the bugs still flying in the server.... <br>
    Thank you for your help.</P>
    </font>
    <p><font size=3 face=arial color=black>PeerWebServer.doc
    <br>
    <p><font size=3 face=arial color=black>CannotFindServer.doc
    <br>
    <p><font size=3 face=arial color=black>HOSTS file is not found
    <br>
    <p><font size=3 face=arial color=black>LMHOSTS file
    <br>
    <p><font size=3 face=arial color=black>How to Setup PWS on NT
    <BR>
    <p><font size=3 face=arial color=black>Issdmin doc</BR>
    Please be patient while the document is download....</font>
    <font size=3 face=arial color=black><br>If you have any ideas please drop me a
    few words at [email protected] </font><br>
    <br>
    <br>
    </p>
    <p><!--#include file="Hits.asp"--> </p>
    </body>
    </html>
    ========= END OF FILE ===============

    Hi!
    This is a possible solution to your problem.
    import java.io.*;
    class AddressExtractor {
         public static void main(String args[]) throws IOException{
              //retrieve the commandline parameters
              String fileName = "default.html";
              if (args.length != 0)      fileName =args[0];
               else {
                   System.out.println("Usage : java AddressExtractor <htmlfile>");
                   System.exit(0);
              BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
              StreamTokenizer st = new StreamTokenizer(in);
              st.lowerCaseMode(true);
              st.wordChars('/','/'); //include '/' chars as part of token
              st.wordChars(':',':'); //include ':' chars as part of token
              st.quoteChar('\"'); //set the " quote char
              int i;
              while (st.ttype != StreamTokenizer.TT_EOF) {
                   i = st.nextToken();
                   if (st.ttype == StreamTokenizer.TT_WORD) {          
                        if (st.sval.equals("href")) {               
                             i = st.nextToken(); //the next token (assumed) is the  '=' sign
                             i = st.nextToken(); //then after it is the href value.               
                             getURL(st.sval); //retrieve address
              in.close();
         static void getURL(String s) {     
              //Check string if it has http:// and truncate if it does
              if (s.indexOf("http://") >  -1) {
                   s = s.substring(s.indexOf("http://") + 7, s.length());
              //check if not mailto: do not print otherwise
              if (s.indexOf("mailto:") != -1) return;
              //printout anything after http:// and the next '/'
              //if no '/' then print all
                   if (s.indexOf('/') > -1) {
                        System.out.println(s.substring(0, s.indexOf('/')));
                   } else System.out.println(s);
    }Hope this helps. I used static methods instead of encapsulating everyting into a class.

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • Having trouble reading specific lines from a text file and displaying them in a listbox

    I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
    occurred in mscorlib.dll"
    Below is the code from that form. 
    Option Strict On
    Option Infer Off
    Option Explicit On
    Public Class frmInventoryReport
    Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
    Dim intTemp As Integer
    intTemp = lineNumber
    Return lines(lineNumber - 1)
    lineNumber = intTemp
    End Function
    Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
    For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
    If fileName.ToLower().Contains(phrase.ToLower()) Then
    Return True
    End If
    Next
    Return False
    End Function
    Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    End Class
    Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!

    Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
    Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it.  Is there anything other than name and cage number that should be associated with each animal?
    You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple.  Here's a simple class example:
    Public Class Animal
    Public Property Name As String
    Public Property Cage As String
    Public Overrides Function ToString() As String
    Return String.Format("{0} - {1}", Name, Cage)
    End Function
    End Class
    With that you can use a routine like the following to loop through all of the files and read each one:
    Dim animals As New List(Of Animal)
    Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
    For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
    Using reader As New System.IO.StreamReader(filePath)
    Dim lineIndex As Integer = 0
    Dim currentAnimal As New Animal
    While Not reader.EndOfStream
    Dim line As String = reader.ReadLine
    If lineIndex = 0 Then
    currentAnimal.Name = line
    ElseIf lineIndex = 22 Then
    currentAnimal.Cage = line
    Exit While
    End If
    lineIndex += 1
    End While
    animals.Add(currentAnimal)
    End Using
    Next
    'do something to display the animals list
    Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView.  If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
    There are lots of options depending on what you want and what all you need to do.
    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

  • Reading Multiple lines using File Adapter in PI 7.1

    Hi Friends,
    We are using PI 7.1 Service pack 4, scenario is File to IDOC .
    I am using  Sender File Adapter with File content conversion for fixed lengths to read file from FTP XI-SAP.
       File Format :
      EDI_DC40 , A, B, C, D, E
      E1WPU01, F, G,H, I
      E1WPU02 , J,K,L
      E1WPU02 , J,K,L
    I have maintained Fcc parameters . I am able to read files for mulitple rows when manually set the count in recorset structure
    like :
    Recordset Structure : EDI_DC40,1, E1WPU01,1, E1WPU02,2...
    Problem is when I set * in  Recorset Structure  : EDI_DC40,1, E1WPU01,,E1WPU02,
    Nothing is coming .
    Could anyone help me how to resolve this issue.
    Regards,
    Vijay

    Hi Vijay,
    As u mentioned in earlier post...
    keyfieldName = TABNAM
    EDI_DC40.fieldNames :
    EDI_DC40. fieldFixedLengths:
    EDI_DC40.keyFieldValue :
    E1WPU01.fieldNames :
    E1WPU01.fieldFixedLengths:
    E1WPU01.keyFieldValue
    E1WPU02.fieldNames :
    E1WPU02.fieldFixedLengths:
    E1WPU02.keyFieldValue
    Here actually you are trying to get the key field value even from EDI_DC40 and E1WPU01 also....
    So obviously u dnt have those values in that rows so.. it cannot get the rows....
    So please u try this one..... The same FCC but remove the 2 lines.... for EDI_DC40 and  E1WPU01
    keyfieldName = TABNAM
    EDI_DC40.fieldNames :
    EDI_DC40. fieldFixedLengths:
    E1WPU01.fieldNames :
    E1WPU01.fieldFixedLengths:
    E1WPU02.fieldNames :
    E1WPU02.fieldFixedLengths:
    E1WPU02.keyFieldValue
    I hope this wil solve ur problem..
    Lemme know if any issues...
    Thanks & Regards,
    H.L.Babu

Maybe you are looking for

  • Why can I not open pdf files in Safari? All I get is a black screen.

    Suddenly Safari will not allow me to open pdf-files, and I have gathered from other discussions that it is a problem. I removed Adobe Reader, to see if Preview would kick in but it did not work. Any suggestions? Thankful for any ideas.

  • SOAP adapter redirecting 50000 port posts to 50001 automatically

    Hi, We have the SSL provider activated because we do encrypted messaging with external partner, but we also have internal systems posting via the SOAP adapter without SSL. They are trying to do this via port 50000, but since SSL is active, the messag

  • [SOLVED] Broken backlight brightness adjustment on x220 after recent-

    Hi. I'm no longer able to adjust backlight brightness with hotkeys and xbacklight. I believe issue appeared after update to linux-3.16. Brightness adjustment keys are detected correctly in xev. Echoing brightness value to /sys/class/backlight/intel_b

  • User based deployment not working

    Looking to make app available to user IDs. I have the user IDs into a user collection and making package available to collection.  Content is on the distribution points. It isn't showing up on client.  Package is set to be available, so I'm not getti

  • Date of the Stock 'Category :CC'

    Hi,        When a stock (Category: CC) is transferred from R/3 to APO , I can view the  stock quantity with the current date in the IO_TIME field in the product view. But suddenly I noticed for all the product location the date has changed to 01.01.1