Reading Last line(record) from a txt file ina java

Hi,
I want to retrive the last line from a txt file.Can anybody help me??
Thanx in advance

In order to read the last line you must read all the lines before it. To read lines you can use the BufferedReader and LineNumberReader classes.
Here's an example of how to read lines of text from a file:
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

Similar Messages

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • I can't read in a date from a txt file

    Im not sure of the code needed to read in a date from the text file, this is an example of the text file:
    1
    2
    2003
    ie,
    day
    month year
    I have to read in this date, this is the set method for the date:
    public void setPurchaseDate (int d, int m, int y)
    new Date(d,m,y);
    And this is the code that I have tried using to readin the date:
      PurchaseDate=(Integer.parseInt(line),Integer.parseInt(line),Integer.parseInt(line));now i know its wrong, I just dont know what the code should be!!
    Cheers

    ok, I am going to go through it and see what values I can and cant read in, here is the code i am trying to use:
    private void addx()
           FileReader fin;
           int noBooks;
           int itemNum;
           String title;
           String subject;
           double costNew;
           double costPaid;
           String isbn;
           double sellingPrice = 0;
           int noAuthors;
           int day;
           int month;
           int year;
            String seperator = "#";
            Book[] book = new Book[9];
            try
                fin = new FileReader("Books.txt");
                BufferedReader buff = new BufferedReader(fin);
                String line = buff.readLine();
                int count= 0;
                //read in Number of books
                noBooks=Integer.parseInt(line);
                while( line != null)
                    //Read in item number
                    itemNum = Integer.parseInt(line);
                    //Read in title
                    title = buff.readLine();
                    //Read in number of authors
                    noAuthors=Integer.parseInt(line);
                    //Read each line in as an author until number of authors reached
                    ArrayList authors = new ArrayList();
                    for(int i=0; i < noAuthors ; i++)
                        authors.add(buff.readLine());
                    //Read in cost new
                    costNew = Double.parseDouble(line);
                    //Read in subject
                    subject = buff.readLine();
                    //Read in ISBN
                    isbn = buff.readLine();              
                    //Read in purchase day
                    day = Integer.parseInt(line);
                    //Read in purchase month
                    month=Integer.parseInt (line);
                    //Read in purchase year
                    year = Integer.parseInt (line);
                    //Read in cost paid
                    costPaid = Double.parseDouble(line);
                    line = buff.readLine();
                    //Pass date, month and year values to array
                    Date purchaseDate =new Date(day,month,year);
                    //Pass values to constructor
                    if (line.equals(seperator))
                        book[count++] = new Book(itemNum, title, authors, subject, purchaseDate,costNew,costPaid,isbn, sellingPrice,noAuthors);
                  // line = buff.readLine();
                System.out.println(book.toString());
            catch(Exception ex)
                System.out.println(ex.toString());
             }

  • Inserting records from a txt file to a database table

    I would like to know how to insert records from a file (txt) to a database table through a java application?

    [BufferedReader |http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html] and PreparedStatement
    IO and JDBC

  • Count from a .TXT file

    Hi Gurs...
    Plx help
    How to get the count - number of records from a .TXT file through Oracle 8i
    EMP.TXT
    EMPNO ENAME
    1 REENA
    2 SUGU
    3 RAJ
    Count(*)=3
    How to get this output in Oracle 8i.
    Thanks in advance
    Gita

    sql>create or replace directory TEST_DIR as 'd:\test';
    Directory created.
    sql>
    CREATE OR REPLACE PROCEDURE rd_file
    AS
    v varchar2(500);
    abc number;
    in_file utl_file.file_type;
    BEGIN
    in_file :=utl_file.fopen('TEST_DIR','sample.txt','R');
    abc := 0;
    loop
      utl_file.get_line(in_file,v);
      abc := abc + 1;
    end loop;
    EXCEPTION
    when no_data_found then
      utl_file.fclose(in_file);
      dbms_output.put_line(abc);
    END ;
    show errors;
    Procedure created.
    No errors
    sql>
    begin
    rd_file;
    end;
    4
    PL/SQL procedure successfully completed
    Message was edited by:
            jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to make this faster?? read millions of record from txt file

    Hi there,
    I got an issue. There is a txt file contains 2 million records, I also got another file contains over 10000 numbers. Now, I need to compare this 10000 numbers with that 2 million records if any records contains a number which belongs to 10000 number set, i retrieve this record and keep it. later on, when i finish the comparison i'll write all the result records into a txt file.
    What kind of data structure shall i use to keep the records and numbers? how to make the comparison quicker? Any idea will do!
    Thanks!

    if i were to do it, i will insert bout the records into the db. then do an sql statement on the two tables to get the results. Then get the rs and output it to another text file.
    just my opinion. not sure if this is faster.
    Message was edited by:
    clarenceloh

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • Populate a table reading the data from a TXT file

    how can I populate a table reading the data from a TXT file?
    thanks

    Hey Kevin!
    Using FORMS.TEXT_IO to bulk load data from a file strikes me as re-inventing the wheel. It is just about justifiable in a self-service environment, but I regard the EXTERNAL TABLE is a better solution for that situation as well.
    The same applies to UTL_FILE. I think the ability to read text with UTL_FILE is primarily intended for read file-based configuration or file manipulation/processing rather than data loading.
    Re-writing a text file into SQL statements is too much like hard work (even with an editor that supports macro definition and regular expressions) for no real benefit. You lose all the bulk load peformance you would get from SQL*Loader. But for QAD I'd probably let you off with it.
    You missed out one obvious alternative: using Java to turn the contents of an XML file into a CLOB and inserting it into a table which is read by a PL/SQL procedure that parses the XML records and insert the retrieved data into a table.
    Stay lucky, APC

  • What is the 'quickest' way to read char data from a txt file

    Hello,
    What is the 'quickest' way to read character data from a txt file stored on the phone to be displayed into the screen?
    Regards

    To be even a bit more constructive...
    Since J2me does not have a BufferedInputStream, it will help to implement it yourself. It's much faster since you read large blocks at ones in stread of seperate chars.
    something line this lets you read lines very fast:
      while ( bytesread < filesize ) {
             length = configfile.read( buff, 0, buff.length );
             // append buffer to temp String
             if ( length < buff.length ) {
                byte[]  buf  = new byte[length];
                System.arraycopy( buff, 0, buf, 0, length );
                tmp.append( new String( buf ) );
             } else {
                tmp.append( new String( buff ) );
             // look in tmp string for \r\n
             idx1 = tmp.toString().indexOf( "\r\n" );
             while ( idx1 >= 0 ) {
                //if found, split into line and rest of tmp
                line = tmp.toString().substring( 0, idx1 );
             /// ... do with it whatever you want ... ////
                tmp = new StringBuffer( tmp.toString().substring( idx1 + 2 ) );
                idx1 = tmp.toString().indexOf( "\r\n" );
             bytesread += length;
          }

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • Reading integers from a .txt file and computing means

    I have a program that uses for loops to produce ten integers (1-10) are returns the average mean, geometric mean, and harmonic mean.
    Now i need to change this program to read integers from a .txt file and return the same data. Basically i need to change my for statements that are incrementing to read the text file.
    Thanks guys.

    You haven't asked a question. You haven't posted code. What are you expecting here?
    But I guess I'll take a stab at it and say you should look at the Scanner class
    http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    or BufferedReader
    http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html
    I'll never understand what makes people come to the forums, create an account, and ask a lazy question, when they could get a great answer much quicker through Google.
    http://www.google.com/search?q=java+file+input (hint: look at the second search result)

  • Read numbers from a .txt file and display them in a graph

    How can I get Labview 7 to read from a txt. file containing a lot of
    coloumns with different datas? There`s only two of the coloumns that are
    interesting to me, the first, that contains the time of the measuring, and
    one in the middle, that contains the measured temperatures. I want Labview
    to read this datas and display them graphicly.
    Thanks from Stale

    Here's one way.
    You can also use the help-> find examples and search for "text".
    2006 Ultimate LabVIEW G-eek.
    Attachments:
    Graph.vi ‏21 KB

  • Reading a PublicKey \ PrivateKey type from a txt file

    Hi,
    i want to read a PublicKey \ PrivateKey type from a txt file and input it into a method.
    How can i read the data from the file while keeping or converting back to PublicKey \ PrivateKey type?
    I'm working with the following:
    generate = KeyPairGenerator.getInstance("ECDSA", "FlexiEC");                              
    generate.initialize(ecParams, new SecureRandom());
    KeyPair keyPair = generate.generateKeyPair();
    ............continues
    **and then i write the keys to the a simple txt file.**
    thanks!
    Edited by: sk16 on Apr 8, 2010 10:03 PM

    So, if i work with the two above is it ok, like:
    generate = KeyPairGenerator.getInstance("ECDSA", "FlexiEC");
                   generate.initialize(ecParams, new SecureRandom());
                   KeyPair keyPair = generate.generateKeyPair();
                   // Pub. and Priv. key objects.
                   PublicKey publicKey = keyPair.getPublic();
                   PrivateKey privateKey = keyPair.getPrivate();
                   // Write keys to separate files.
                   FileOutputStream fos = new FileOutputStream(publicKeyFile);
                   fos.write(publicKey.getEncoded());
                   fos.close();
                   FileOutputStream fos1 = new FileOutputStream(privateKeyFile);
                   fos1.write(privateKey.getEncoded());
                   fos1.close();
    and then for example>>>
    DataInputStream in = new DataInputStream(
              new FileInputStream("publicKeyFile.txt"));
              byte[] encodedPublicKey = new byte[1024];
              in.read(encodedPublicKey);
              in.close();
              X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
              KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "FlexiEC");
              publicKey = keyFactory.generatePublic(encodedPublicKeySpec);

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • What is the smallest data structure record in a .TXT file record to be recognized as an Apple Address Book "Data Card"?

    Hello! This is my first time in this discussion group. The question posed is the subject line itself:
    What is the smallest data structure record in a .TXT file record to be recognized as an Apple Address Book "Data Card"?
    I'm lazy! As a math instructor with 40+ students per class per semester (pCpS), I would rather not have to create 40 data cards pCpS by hand, only to expunge that info at semester's end. My college's IS department can easily supply me with First name, Last name, and eMail address info, along with a myriad of other fields. I can manipulate those data on my end to create the necessary .TXT file, but I don't know the essential structure of that file.
    Can you help me?
    Thank you in advance.
    Bill

    Hello Bill, & welcome aboard!
    No idea what  pCpS is, sorry.
    To import a text file into Address Book, it needs to be a comma delimited .csv file, like...
    Customer Name,Company,Address1,Address2,City,State,Zip
    Customer 1,Company 1,2233 W Seventh Street,Unit 543,Seattle,WA,99099
    Customer 2,Company 2,1 Park Avenue,,New York,NY,10001
    Customer 3,Company 3,65 Loma Linda Parkway,,San Jose,CA,94321
    Customer 4,Company 4,89988 E 23rd Street,B720,Oakland,CA,99899
    Customer 5,Company 5,432 1st Avenue,,Seattle,WA,99876
    Customer 6,Company 6,76765 NE 92nd Street,,Seattle,WA,98009
    Customer 7,Company 7,8976 Poplar Street,,Coupeville,WA,98976
    Customer 8,Company 8,7677 4th Ave North,,Seattle,WA ,89876
    Customer 9,Company 9,4556 Fauntleroy Avenue,,West Seattle,WA,98987
    Customer 10,Company 10,4 Bell Street,,Cincinnati,OH,89987
    Customer 11,Company 11,4001 Beacon Ave North,,Seattle,WA,90887
    Customer 12,Company 12,63 Dehli Street,,Noida,India,898877-8879
    Customer 13,Company 13,63 Dehli Street,,Noida,India,898877-8879
    Customer 14,Company 14,63 Dehli Street,,Noida,India,898877-8879
    Customer 15,Company 15,4847 Spirit Lake Drive,,Bellevue,WA,98006
    Customer 16,Company 16,444 Clark Avenue,,West Seattle,WA,88989
    Customer 17,Company 17,6601 E Stallion,,Scottsdale,AZ,85254
    Customer 18,Company 18,801 N 34th Street,,Seattle,WA,98103
    Customer 19,Company 19,15925 SE 92nd,,Newcastle,WA,99898
    Customer 20,Company 20,3335 NW 220th,2nd Floor,Edmonds,WA,99890
    Customer 21,Company 21,444 E Greenway,,Scottsdale,AZ,85654
    Customer 22,Company 22,4 Railroad Drive,,Moclips,WA,98988
    Customer 23,Company 23,89887 E 64th,,Scottsdale,AZ,87877
    Customer 24,Company 24,15620 SE 43rd Street,,Bellevue,WA,98006
    Customer 25,Company 25,123 Smalltown,,Redmond,WA,98998
    Try Address Book Importer...
    http://www.sillybit.com/abee/

Maybe you are looking for