Need help, reading next file line

i have a file that i am reading using this code, this code reads only string on the first line
i wnat it to read the second line from the file when the method is called again
private transactionLine="";
public void fileReading()
try
          try
               FileInputStream finstr = new FileInputStream(userFile);          
          BufferedInputStream bfinstr = new BufferedInputStream(finstr);
          DataInputStream dainsstr = new DataInputStream(bfinstr);
                         transactionLine = dainsstr.readLine();     //holds the transaction line
                         System.out.println(transactionLine);
          catch(FileNotFoundException fnf)
               System.out.println("File not found");
               userFile=userInput();
               fileReading();
               catch(IOException ioe)
                    System.out.println("io exception at point 1");//point 1

How big is your file ?
If it's small file, you can just create a static counter that reads the lines (again and again).
Else if its a little bigger file, you might want to put it in a vector (once read, always there).
If its a very large file, then you might work with RandomAccessFile, and you'll have to know how the file is structered.
ReadFile and ReadFile2 are 2 examples of read the lines, or place in vector.
good luck!
import java.io.*;
public class ReadFile
    private File file = null;
    private static int executed = 0;
    public ReadFile(String fileName)
        //find the file
        File f = new File(fileName);
        if( !f.exists() )
            System.out.println("Cannot find the specified file ( " + fileName + ").");
        else
            this.file = f;
    public String getTransactionLine()
        executed++;
        String line = "";
        if( this.file == null || executed < 1 )
            return line;
        try
            //create a reader
            BufferedReader br = new BufferedReader( new FileReader(file) );
            int counter = 1;
            //read the lines depends on time it been executed
            while( (line=br.readLine())!=null )
                if( counter++ == executed )
                    break;
            //if exceeded the amount of lines in the file
            if( executed >= counter )
                line = "Could not read more, the file contains only " + (counter-1) + " lines.";
        catch (Exception ex)
            ex.printStackTrace();
        return line;
    public static void main(String[] args)
        ReadFile rf = new ReadFile("c:\\debugLog.txt");
        //read 1
        String transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 2
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 3
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 4
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 5
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
import java.io.*;
import java.util.Vector;
public class ReadFile2
    private static int executed = 0;
    private Vector lines = null;
    public ReadFile2(String fileName)
        //find the file
        File file = new File(fileName);
        if( !file.exists() )
            System.out.println("Cannot find the specified file ( " + fileName + ").");
            return;
        //this vector will contain all lines.
        lines = new Vector();
        try
            //create a reader
            BufferedReader br = new BufferedReader( new FileReader(file) );
            String line = "";
            //read the lines and add them to a vector (lines).
            while( (line=br.readLine())!=null )
                lines.add(line);
        catch (Exception ex)
            ex.printStackTrace();
    public String getTransactionLine()
        String line = "";
        try
            line = (String) lines.get(executed++);
        catch( Exception ex )
            line = "Could not read more, the file contains only " + (executed-1) + " lines.";
        return line;
    public static void main(String[] args)
        ReadFile2 rf = new ReadFile2("c:\\debugLog.txt");
        //read 1
        String transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 2
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 3
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 4
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
        //read 5
        transactionLine = rf.getTransactionLine();
        //output:
        System.out.println(transactionLine);
}

Similar Messages

  • Need help reading raw files!

    Help please!  Cannot read raw files of my Nikon D5000.  Have downloaded Camera Raw 5.3 and followed instruvctions.  5.3 supports the D90 which is supposedly essential the same.  Any suggestions?

    Read the posts in the following link:-
    http://www.elementsvillage.com/forums/showthread.php?p=463255#post463255
    Try the DNG converter or the DPP software supplied with your camera until ACR 5.4 is finalized, as suggested in the posts.
    I have read that there is a way to get the Release Candidate 5.4 installed in PSE 6/7 but you need some skills in understanding computer files.

  • Need help reading a file ~!

    Hi,
    I cant seem to read this file. It compiles without errors, but i get a java.nullPointerException when i run it. My data file looks like this:
    5
    class1
    class2
    class3
    class4
    class5
    1-2 1-3 2-4 3-4 4-5
    here is my code to read the file:         public void Read(String fileName) {
                    try {
                            String num; //number of cells
                            String cells; //cell data
                            FileReader file = new FileReader(fileName);
                            BufferedReader in = new BufferedReader (file);
                            num = in.readLine();
                            number = Integer.valueOf(num).intValue(); //converts string to int
                            co = new ClassObject[number];
                            System.out.println("There are " + number + " total classes");
    //## PROBLEM OCCURS IN THIS FOR LOOP which reads in the 5 names of classes
                            for (int b=0; b<number; b++){
                                   co.className = in.readLine();
    } //#### end of problem
    while ((cells = in.readLine()) != null) {
    StringTokenizer st1 = new StringTokenizer(cells, " ");
    while (st1.hasMoreTokens()) {
    String ST1 = st1.nextToken();
    StringTokenizer st2 = new StringTokenizer(ST1, "-");
    String ST2 = st2.nextToken();
    co[x] = new ClassObject();
    co[x].classNumber = Integer.valueOf(ST2).intValue();
    ST2 = st2.nextToken();
    co[x].classRelation = Integer.valueOf(ST2).intValue();
    x++;
    } catch (IOException e) {
    System.out.println("Warning: Cannot Read File");
    System.exit(0);
    setPositions();
    thanks for any help!

    Sorry, I didn't notice your comment in the code.
    for (int b=0; b<number; b++){
      co[ b]= new ClassObject();
      co[ b].className = in.readLine();
    }

  • Reading a file line by line and executing the code

    I need to read a file line by line and execute them simultaneously.
    I use BufferedReader for reading , but for executing i tried a lot , but could not find a solution.
    Kindly help and try to brief me.

    If you're hoping to execute lines of java source code on the fly...then forget it. Java is a compiled language. It doesn't have an "eval" statement like other languages.
    Now, you can write an interpreter for a language in Java. And I suppose you could write an interpreter for Java in Java (although at that point, you might as well choose to interpret a different language; it would probably be easier). But that would be a pretty big task.

  • [Urgent] How to let FileAdapter to read next file after a customized period

    Dear friends,
    We are using SOA Suite 11.1.1.5 and use FileAdapter in BPEL Process to read files.
    The file adapter in BPEL Process need to handle 14 inbound different files every batch time. And we want to let File Adapter to start reading next file after every 5 minutes. How can we achive this?
    We tried the MinimumAge and SingleThreadModel properties, but seems no use.
    Thank you in advance.
    Regards,
    Tony

    Hi Tony,
    I think this can help you. Set the following JCA property in File/FTP Adapter .jca file. This will restrict the max no. of files to be read every polling cycle. Set the polling frequency to 5 mins.
           <property name="MaxRaiseSize" value="1"/>Let me know if any problems.
    Regards,
    Neeraj Sehgal

  • Need to read text file content and have to display it in multiline text box

    dear all,
    Need to read text file content and have to display it in multiline text box.
    actually im new to file handling. i have tried up to get_line and put_line.
    in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
    TEXT_IO.GET_LINE (in_file,linebuf);
    i dont know how to assign this get_line function to text item
    pls help me in this regards,

    Simply write:
    in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
    TEXT_IO.GET_LINE (in_file,linebuf);
    :block2.t1 := chr(10)||:block2.t1||chr(10)||linebuf;
    chr(10) --> is for new line character

  • Read the file line by line from upload

    Hi Guys,
    Need help... I creating a web application that has a upload capability. What I want to do is this...
    I want to upload a file (but not save it). What I'm going to do is just read the file line by line and save these data to the database. How can I do this? (BTW, I'm using struts (FormFile)).
    Please guide me please!
    Thanks.

    i think u should obtain a inputstream from request object and then save it to the database using BLOB object.

  • What is the best way to read a file line by line?

    Hello, everyone!
    I want to read a file line by line, i.e. each time, a line of a text file is read and stored as a String object and the String object will be manipulated (parsed) later.
    I have found that FileInputStream does not have a function which is responsible for reading a line each time from a text file. Anyone have good suggestions?
    Best regards,
    George

    I always use the following example.. mayb that would help you as well
    File fid = new File(fileName);
    if (fid.exists())
            fr = new FileReader(fid);
            br = new BufferedReader(fr);
             while((txtstr= br.readLine()) != null)
    }

  • Automatically read next file in folder

    HI I am trying to read in files and use the attached vi to calculate the area under the curve.  everything works, except that I would like the functionality of being able to automatically select the "next file" or the "previous file" with out having to reopen user dialogue.  Any help would greatly be appreciated. 
    Solved!
    Go to Solution.
    Attachments:
    Integrate data ___ read next file WIP.vi ‏99 KB

    I don't see where you determine what the first file is to be processed.
    You have various indicators called name, appended path, and stripped path.  You seem to be jumping back and forth on creating paths, but I don't see where you initially determine what is the file.  I think you have problems with misuse of local variables that lead to race conditions where you don't know what is the value in the local variable because it is and when a data value was last written to the indicator.  This really manifests itself in the file name scheme.  You have a local variable of appended path that determines the stripped path and name and puts them into the indicator terminals.  But simulataneously, you are using local variables of stripped path and name to determine the value to put in the appended path indicator terminal.
    I think you have a lot of the correct elements in there.  List Folder is going to give you the list of files in the folder.  I don't know how you determine what Next file is vs. Previous file.  Do you want it to be alphabetical, by file date, or just whatever order that the operating system returns the files?
    Once you have an array of files (from list folder) then using the integer wire to determine which of the elements you want to use is correct.  But you aren't quite doing that.  You are taking the Name local variable, turning that string into an array (which will have exactly one element) and using the index of element (again a local variable) to either return that name back again, or an empty string in the event that the index element is greater than zero.
    Overall, you have a lot of things happening in parallel when they are really sequential processes.  As a result, you are using local variables to pass data back and forth between your two case structures, but there is no control over whether the data is fresh from that loop iteration, or stale from the previous loop iteration.
    Set up a flowchart as to what the sequence of steps would be and program to that.  You may want to look into event structures to handle button presses for next file, previous file, and read data, so that it executes the reading and analyzing of the files, and also updates the file index either 1 higher or lower when those buttons are pressed.

  • How to read text file line by line...?

    how to read text file line by line, but the linefeed is defined by user, return list of string, each line of file is a item of list?
    please help me.
    Thanks very much

    Brynjar wrote:
    In Groovy, you would do something like:
    linefeed = "\n" //or "\r\n" if the user chose so
    lines = new File('pathtofile').text.split("${linefeed}")This is one of the things that has always annoyed me about Sun's sdk, i.e. the lack of easy ways to do things like that. You always end up making your own utilities or use something like Apache's commons.io. Same goes for jdbc and xml - I'll wait for appropriate topics to show how easy that is in Groovy :)I generally agree, but what I really don't like about the Groovy text-file handling niceties: They don't care about encoding/always use the default encoding. And as soon as you want to specify the encoding, it gets a lot more complex (granted, it's still easier than in Java).

  • How to read a file line by line in UTL

    Hi All,
    DECLARE
    fileID UTL_FILE.FILE_TYPE;
    strbuffer VARCHAR2(100);
    BEGIN
    fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
    UTL_FILE.GET_LINE (fileID, strbuffer);
    dbms_output.put_line(strbuffer);
    END;
    By this program I can read only first line of the file. I want to read the file line by line.
    Thanks
    Sunil

    try this
      DECLARE
        fileID UTL_FILE.FILE_TYPE;
        strbuffer VARCHAR2(100);
      BEGIN
        fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
        if utl_file.is_open(fileID) THEN
          loop
            UTL_FILE.GET_LINE (fileID, strbuffer);
            dbms_output.put_line(strbuffer);
            if strbuffer IS NULL THEN
              exit;
            end if;
          end loop;
        end if;
      END;note: untested.

  • I need to read Pages files but  I can't install Pages on osx 10.6

    I  need to read Pages files, but I can't install Pages because I have OSX 10.6.  Is there some version that will work?

    You can get iWork 09 on the net. You haven't had Pages before? Who is sending you Pages documents? Ask them to export the document to Word or Rtf and you will be able to read the documents in TextEdit, which you have on your computer

  • Need help reading burn CDR mp3 and dvdrw from my superdrive

    my Super Drive was fine untill i upgrade to Maverick now it wouldnt  read the music on all of my burn cdr disk and dvdrw . ALso .need help  reading my external 2TB External Ntfs Hard drive.....

    To many conflicting information...
    my Super Drive was fine untill i upgrade to Maverick
    Per your system profile: "Mac mini, Mac OS 9.1.x"
    Mac Minis do not have a superdrive.  You also posted in the Intel iMac forums.
    Please correct and/or update so that you will be provided w/the correct troubleshooting suggestions.

  • My file has insert command and i want to read that file line by line in sql

    myfile.txt
    insert into emp values(100,200,"sumedh",11);
    insert into emp values(101,200,"amit",11);
    insert into emp values(102,200,"sam",11);
    insert into emp values(103,200,"ram",11);
    insert into emp values(104,200,"stev",11);
    I want to read this file line by line and enter this value in emp table.

    Why did you begin this thread in security.
    just like
    sqlplus <schema_owner>/<password>@<your_sid> @<path_to/myfile.txt>

  • Need help reading files from a simple applet

    hi everyone,
    i have the following problem while trying to read from a file:
    java.security.AccessControlException: access denied (java.io.FilePermission dr.xml read)
    this problem shows up only when loading applet from a browser... if i use appletviewer everithing is ok.
    this is the code:
            cycle = new String[2];
            phase = new String[8];
            v = new Vector();
            int temp;
            try {
                try {
                    fis = new FileInputStream("dr.xml");
                    while ((temp = fis.read()) > 0) {
                        buf += (char) temp;
                    fis.close();
                    fis = null;
                } catch (java.io.FileNotFoundException ex) {
                    System.out.println("File does not exist. ");
            } catch (java.io.IOException ex) {
                System.out.println("error. ");
                ex.printStackTrace();
            }thanks

    You don't have access to the file system. Think about it, you visit a web page and an applet starts reading your files? That's a HUGE security risk.
    That said, I think you can do this if you have a signed/trusted applet. Google "signed applets" and "certificates"

Maybe you are looking for

  • How to read in a text file of race lap times....

    How do i read in a text file containing lap times from a race for one driver? I have the times down 1 column and look like this. I then want to add the times up to get a total race time. I have been looking at the Calendar class and the simpleDateFun

  • 11.0.3 11x17 multi page bug

    I recently upgraded everyone from a wide range of versions to 11.0.3 with a group policy.  This wasn't a problem in the past. Details Multi page PDF, all pages are 11x17 Windows 7 Pro x64 PCs Symptom When printing the first page it prints the first p

  • Screen name recovery

    I can't remember the screen name I used to sign in to the Minecraft game I purchased, and I can't figure out how to recover it or my password. Can someone please help me get them sent to my e-mail? THANK YOU!

  • The iTunes library file cannot be saved. An unknown error occurred (-50).

    I launch iTunes, I get "Updating iTunes library" and then, "The iTunes library file cannot be saved. An unknown error occurred (-50)." This started happening after I upgraded to iTunes 7.3. Things seem to work OK, but my artwork was rearranged in cov

  • Where is this elusive DV-AVI Type II export setting?

    Using PE4... Recent threads on exporting parts of clips mention exporting to "DV-AVI Type II" and unchecking "Recompress" etc.  As far as I have found, I have three AVI options available via File - Export - Movie - Settings - General: Uncompressed Mi