Read to get the last line from a File

Hi
I am sending in a clarification , hoping that I get an efficient solution from the group, should somebody have come across this scenario and implemented.
How to read or get the last line from a text file , which usually have a no of records, without actually reading or looping through all the lines
I know there is some solution with the RandomAccessFile, but given there can be some encoding issues or so.
Please let me know if somebody have implemented the same.
Thanks n advance

The character encoding could, indeed, be an issue especially with UTF-8. I think what I'd do is to create a byte array with the encoded, expected end of line sequence in it and work on the file in bytes. For example, seek to the last 100 bytes of the file, read those bytes and look for an EOL sequence backwards. If not found read the previous 100, 200, 400 bytes etc. until you do find an end of line. Then seek to after the EOL and read normally. Remember an EOL sequence might cross a boundary.
UTF-8 would be a problem, especially with a unix format file because you might mistake part of a multi-byte sequence for '\n'. To be reliable on UTF-8 you'd need to go back three characters looking for sequence start markers (has the previous character got the top bit set, or the one before that the first two bits set, or the one before that the top three bits). Or you could just react to an encoding exception and try another position.

Similar Messages

  • Read in the last line of a file

    Can I use the "Read from File " vi to read ionly the last line of the file? If so, how? Thanks in advance for the help
    [email protected]

    Reading the "last line" of a file implies that you are dealing with an humanly readable ASCII text file and there are special characters (/n or /r or a combination of the two) that signify line breaks.
    You can only start reading from a certain byte offset using file I/O. Unless all your lines are equal lenght, It is impossible to find the start of the last line without reading every character leading up to it in one way or another.
    So in the most general case, you would need to read the entire file and find the last linefeed.
    HOWEVER: Typically, lines are not infinitely long, so if you have an upper estimate of line lenght, you can read a slightly longer tail from the end of the file and find the last linefeed there. You can probably modify the VI I posted here for your purpose, just use an appropriate length. Message Edited by altenbach on 06-08-2005 10:42 AM
    LabVIEW Champion . Do more with less code and in less time .

  • Get the last query from the current user

    Is there a way to get the last query of the current user, so every query could be log with a database trigger?
    Let's just say I execute:
    DELETE xxxx;
    I tried :
    SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'));
    But the result of this query is :
    'SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'))'
    Is there a way to execute a query that would return :
    'DELETE xxxx'
    Thanks

    You could join SQL_ADDR in v$session with ADDRESS in v$sqlarea to determine the SID that executed that SQL statement last. Note that PREV_SQL_ADDR in v$session will indicate the previous SQL he executed. Though you would have to look at these tables very often to get all SQL statements issued. One note here, I think if a different user ran the SAME SQL with just bind var differences the SQL_AREA will only show the last user’s information that executed it.
    BTW - it will show deletes also...

  • Getting the visible lines from a JTextArea

    I'm using a JTextArea with a fixed size. I've used the setLineWrap(true) and setWrapStyleWord(true) methods on this JTextArea, so when the user types in some text longer than the visible width, it will wrap into the next line. I need to get each visible line from the JTextArea to create a String array of text lines.
    I mean visible text lines (lines visibly separated in the JTextArea), not real text lines separated by a line break character as "\n".
    How can I do this?

    This information is supposed to be contained in the View information of the component. But as far as I can tell it doesn't work for a JTextArea.
    So if you can use a JTextPane then check out the "getWrappedLines" method in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
    Basically, a View exists for each line in the Document and then each line may have multiple views if the line needs to wrap. So the basic code just count the number of views within each line but you can change the code to get each view separately. Once you have each view you can get the start and end of the text from the document that this View represents.
    Or if you need to use a JTextArea then you can calculate the starting offset of each each line with respect to the model. You can use the viewToModel(..) method to get the starting offset of each line. We know that each line in a text area is a fixed height, so the starting offset of the first line would be modelToView(0, 0); If the line height is 16, then the starting offset of the second line would be modelToView(0, 16), etc. Once you know the starting offset of each line you can subString out the text for each line.

  • How to get the last record from the database

    I am using MS Access database and Swings as GUI. I want to get the last record of a particular column from the table and store it as a varaible.

    Hi
    To get Last record of resultset, you have pass some parameter in constructor of CreateStatement.In such case Resultset should be scrollable and Readonly
    Example
    objStatement=objCon.createStatement ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    mwwResultSet=cwwStatement.executeQuery(mwwSqlQuery);
    while(mwwResultSet.next())
    if(mwwResultSet.isLast())
    //Fetch the required column record.
    String abc=mwwResultSet.getString(1);
    I think this will work. Try it.
    bye

  • Getting the last action from a managed bean

    Is it possible to get the last action that was submitted from within a backing bean.
    I have an application that has a context specific menu at the top of the page. The context menu is generated using a backing bean which is called from a tiled jsp, called contextmenu.jsp.
    The context menu backing bean needs to know what page it is on so that it can generate the correct menu, so is it possible to get hold of the last action submitted, or the current page from within the backing bean?
    Any help would be much apprecieated.
    Jamie Cash

    Thanks for your help,
    but ...
    We will be developing over 200 jsps and don't want to load the development effort with a backing bean for each jsp.
    The solution that I finally arrived at is using the following code in the menubean to get the view id, and make the decision based on that.
    public NavigationMenuItem[] getContextMenu()
         //Get view id
              String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
              logger.debug("view id: " + viewId);
              //Menu
              NavigationMenuItem[] contextMenu = null;
              if(viewId.equals("/home.jsp"))
                   .... Code to get context menu from Stateless Session bean     
              //Return menu
              return contextMenu;
    Regards
    Jamie

  • Need help with java File IO ( Removing the first line from a file )

    Hi guys ,
    I am currently doing a project in which I need to extract out the values from the second line of a file to the end. The question is how do I ignore the first line ??
    I thought of two possible answers myself. One is to use randomaccessfile to read and rewrite. But the file may be HUGE so storing the whole file in memory is not a very good idea.
    Second is to jump to second line before doing while ((str = in.readLine()) != EOL) ... or just delete the first line from the file. Can anyone suggest a better solution or show me some sample codes ? Thanks.
    regards
    billyam

    Just skip the first line (bufferedReader.readLine()), add a comment, and then handle the rest of your file

  • Trying to get the last row from a resultset

    Hi,
    I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
    My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
    I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
    I've tried a variety of things and most seem to return the first row, not showing the updated values.
    Or, if it does work, it takes to long to load, and i get an error.
    here is the working code;
    Object m = machCBX.getSelectedItem():
    try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
    ResultSet.TYPE_SCROLL_INSENSITIVE,  //tried both INSENSITIVE and SENSITIVE
    ResultSet.CONCUR_READ_ONLY);
    last.setString(1, String.valueOf(m));
    rs. = last.executeQuery();
    if(rs.isAfterLast) == false ) {
    rs.afterLast();
    while(rs.previous()) {
    String p = rs.getString("part");
    int c = rs.getInt("count");
    partJTX.setText(p);
    countJTX.setText(c);
    }this grabs values, but they are not the last entered values.
    Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
    I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
    thanks
    -PD

    OK, you've got a major misunderstanding...
    The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
    Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
    In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
    While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course).

  • Getting the last record from the internal table

    When we use a READ statement it always picks up the first record which fulfill its condition but in my case I want to pick up the last record that fulfills it condition
    I have a internal table like
    id     type
    N1      A
    N1      T
    N1      A
    N1      6 ----> LAST RECORD
    my code is
    read table itab wIth key id = netobjid.
    for eg if netobjid = N1 , then I want to read the last record that corresponds to N1 ie ID N1 TYPE - 6...
    How to do that?

    HI
    actually i have done same requirement like this ...
    Take  one count variable into your internal table ..you pass the number of records into cont variable for every time  u enter the loop .
    Sort the internal table with count variable descending . ( AS we cant sort the internal table with sy-tabix)
    Then use read statement with sy-index = 1 .
    USe below logic ,............
    data  :  count  type i value '0'.
    LOOP at int .
    count = count + 1 .
    endloop.
    sort int count descending .
    read int  with  index = 1 .

  • Not able to get the actual plan from trace file

    Hi all
    I have a Db package and want to get actual execution plan of all the statements in that pakcage it does provides the plan for System's statements but does not displays the plan for Sql statements
    DB version 9.2.0 using the following sequence of insructions
    set timing on
    set serveroutput on
    alter session set events '10046 trace name context forever ,level 12';
    begin
    run_service.collect_data(sysdate);
    end;
    alter session set sql_trace=false;
    exit; ---exit from Sql
    now look at the output
    select distinct obj#,containerobj#,pflags,xpflags,mflags
    from
    sum$, suminline$ where sumobj#=obj# and inline#=:1
    call count cpu elapsed disk query current rows
    Parse 1 0.00 0.00 0 0 0 0
    Execute 1 0.00 0.00 0 0 0 0
    Fetch 1 0.00 0.00 1 1 0 0
    total 3 0.00 0.00 1 1 0 0
    Misses in library cache during parse: 0
    Optimizer goal: CHOOSE
    Parsing user id: SYS (recursive depth: 2)
    Rows Row Source Operation
    0 SORT UNIQUE
    0 NESTED LOOPS
    0 TABLE ACCESS BY INDEX ROWID SUMINLINE$
    0 INDEX RANGE SCAN I_SUMINLINE$_2 (object id 1614116)
    0 TABLE ACCESS BY INDEX ROWID SUM$
    0 INDEX UNIQUE SCAN I_SUM$_1 (object id 319)
    Elapsed times include waiting on following events:
    Event waited on Times Max. Wait Total Waited
    ---------------------------------------- Waited ---------- ------------
    db file sequential read 1 0.00 0.00
    SELECT SEQ_NUM, S_DATE, S_TIME, CSTATUS, G_SERVICE,
    B_REFERENCE, V_REFERENCE, M_PRIORITY
    FROM GL_HIST
    ORDER BY S_DATE DESC, S_TIME DESC
    call count cpu elapsed disk query current rows
    Parse 1 0.01 0.01 0 0 0 0
    Execute 2819 0.37 0.32 0 0 0 0
    Fetch 2819 2.50 20.47 2786 20164 0 2819
    total 5639 2.88 20.81 2786 20164 0 2819
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    Parsing user id: 15550 (recursive depth: 1)
    Elapsed times include waiting on following events:
    Event waited on Times Max. Wait Total Waited
    ---------------------------------------- Waited ---------- ------------
    db file sequential read 2786 0.05 18.19
    latch free 4 0.04 0.06
    UPDATE G_ORIG SET G_SERVICE = :B1
    WHERE
    SEQ_NUM = :B5 AND S_DATE = :B4 AND S_TIME = :B3 AND
    C_STATUS = :B2 AND NVL(G_SERVICE, '+') <> NVL(:B1, '+')
    call count cpu elapsed disk query current rows
    Parse 1 0.00 0.03 0 0 0 0
    Execute 3731 0.74 0.99 261 18712 119 54
    Fetch 0 0.00 0.00 0 0 0 0
    total 3732 0.74 1.02 261 18712 119 54
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    Parsing user id: 15550 (recursive depth: 1)
    Elapsed times include waiting on following events:
    Event waited on Times Max. Wait Total Waited
    ---------------------------------------- Waited ---------- ------------
    db file sequential read 261 0.01 0.19
    latch free 9 0.01 0.04
    COMMIT

    Remove the line alter session set sql_trace=false and just exit/disconnect. The explain plain is contained in the STAT lines in the trace file and are only written when the cursor closes. If you turn off tracing before the cursor closes the STAT lines will not get written.

  • How to read last line from a .txt file?

    Hello
    I have a string: e.g. "my name is John"
    and i wanna verify if this string is equal with the last line from a text file
    for example, if in the txt file i have:
    asdasd
    sdgsdfgasd
    asdfgadfgadf
    sdgasdgsdf
    my name is john
    then it's OK.
    but if i have
    asdgsdfg
    dsfhsdfhsd
    sdgasdfg
    sdgsdg
    my name is Jdfgsdg
    this is not correct
    How should i do this?
    Thanks:)

    Read from the beginning an discard all lines (if you have a small file), or use RandomAccessFile and scan from the end till you find the beginning of the last line.
    Kaj

  • How to select LAST line from a SAP table?

    Hi developers,
    I need to select the last line from a SAP table, NOT from an internal table.
    Something like
    SELECT SINGLE LAST FROM pa00169..
    any help is more than welcome.

    Javier,
    Based on this statement from you:
    "i created a Z table, its a config table that stores some bussines rules, and an id counter, so in order to update that counter i need the last line of the ztable."
    I have one additional solution which is the "text box" approach IF the 'id counter' mentioned above is a numeric data type.
    If so, use an SQL function to get the highest value of ID_COUNTER.
    Then simply add one to it to produce a new, unique, higher-order primary key.
    See below:
    data: l_id_counter like ztable-id_counter.
    data: new_id_counter like ztable-id_counter.
    select max( ID_COUNTER ) from ztable into l_id_counter.
    new_id_counter = l_i_counter + 1.
    Now new_id_counter will be the unique, primary key IF this is the only field in ZTABLE's primary key.
    This will also GUARANTEE that your new record is built correctly.

  • Only getting the last layer of text animation

    Hi, complete newb here. I've watch most of the tutorials and looked thru the forum but didn't see anything addressing this. When I export to swf and then try to view the html code I only get the last line of text animation, the 1st line doesn't appear. Any help would be great. Thanks.

    I'm still not clear what you are describing here. With AE, it's either one or the other, not both. Any element that requires rasterization will also enforce rasterization of other elements, so you essentially end up with a JPEG sequence wrapped in an SWF. This, by all means should render everything as you see in the comp window. From your description it seems to me that you are trying to retain editable SWF objects for further editing in your other programs and naturally, since this is severely limited, not everything comes across. If you cannot resolve this, pretty much your only option is to render a FLV and play it on your website. If you had CS4, you could also use XFL exchange with special preparation (all elements need to be PNG in the main comp) and then convert it in Flash. Another workflow that realyl gives you the best of both worlds without the excess baggage of Flash Pro would be to use Flash Catalyst. You could open your PSD there, animate it and export a slim and optimized SWF directly. Whatever you do, maybe you could read the help sections on SWF and XFL export again. This might help you to figure out where it is going wrong for you from the AE end.
    Mylenium

  • Can I align the last line of a text container to to bottom of a container?

    Is it possible to take the last line in a text container and vertically align it to the bottom? I'm aware that I can justify the entire text container vertically to achieve this effect. However, this means tha every line in the container is now spaced out with increased leading.
    Here's a screen capture of what I mean.
    On the right is a text container without any vertical justification and sized to fit the text. On the left is a text container that I've sized to match the height of the right container. In order to get the last line to align to the bottom I used the Justify vertically option. But my bullets are now spread out.
    Basically I just want the last line aligned to the bottom and the rest of the text above it to be aligned to the top.
    Is there anyway to do this with just one text container? Or will I be forced to used two text containers?
    I'm using InDesign CS5 if that matters.

    I think I'd do this with a two-cell table.

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

Maybe you are looking for

  • G5 clicks off when 15" or 17" ADC Display is connected

    I just bought a 17" ADC Apple Display to use with my Dual G5 2.5Ghz. My 15" ADC Apple Display was working great. When I attached the 17", I heard a clicking sound within the G5. It then wouldn't power up. I attached a DVI to VGA Adapter and it powere

  • Issue with creating a text box from a loop

    I was hoping someone could take a look at this code and maybe help me find out why this isnt working. What I am trying to do is: (NOTE: I have used a few differents scripts and combined them, so the code may not be the greatest). Pull Data from a PHP

  • Unable to Connect to database server

    Hi All, I have installed Oracle 11g R2 database, I used it for almost a month now and then today when I tried to log in into it I am getting this error. An error was encountered performing the requested operation: Listener refused the connection with

  • Zen Vision M 60gb 600$ !?!?!?!?

    ok so i located a website from creative that is the only place in the world that sells the 60gb ZVM and everything on the website is WAY overpriced what is up with that heres the website to look at it... sg.store.creative.com i figured the ZVM would

  • Downloaded "Yes Man"but it has not shown up

    I downloaded "Yes Man"the film from itunes however it does not say if it is downloading and there is no purchase history neither:S.