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

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){
        }

  • How to read specific lines from a text file using external table or any other method?

    Hi,
    I have a text file with delimited data, I have to pick only odd number rows and load into a table...
    Ex:
    row1:  1,2,2,3,3,34,4,4,4,5,5,5,,,5  ( have to load only this row)
    row2:   8,9,878,78,657,575,7,5,,,7,7
    Hope this is enough..
    I am using Oracle 11.2.0 version...
    Thanks

    There are various ways to do this.  I would be inclined to use SQL*Loader.  That way you can load it from the client or the server and you can use a SQL*Loader sequence to preserve the row order in the text file.  I would load the whole row as a varray into a staging table, then use the TABLE and MOD functions to load the individual numbers from only the odd rows.  Please see the demonstration below.
    SCOTT@orcl12c> HOST TYPE text_file.csv
    1,2,2,3,3,34,4,4,4,5,5,5,,,5
    8,9,878,78,657,575,7,5,,,7,7
    101,201
    102,202
    SCOTT@orcl12c> HOST TYPE test.ctl
    LOAD DATA
    INFILE text_file.csv
    INTO TABLE staging
    FIELDS TERMINATED BY ','
    TRAILING NULLCOLS
    (whole_row VARRAY TERMINATED BY '/n' (x INTEGER EXTERNAL),
    rn SEQUENCE)
    SCOTT@orcl12c> CREATE TABLE staging
      2    (rn         NUMBER,
      3     whole_row  SYS.OdciNumberList)
      4  /
    Table created.
    SCOTT@orcl12c> HOST SQLLDR scott/tiger CONTROL=test.ctl LOG=test.log
    SQL*Loader: Release 12.1.0.1.0 - Production on Tue Aug 27 13:48:37 2013
    Copyright (c) 1982, 2013, Oracle and/or its affiliates.  All rights reserved.
    Path used:      Conventional
    Commit point reached - logical record count 4
    Table STAGING:
      4 Rows successfully loaded.
    Check the log file:
      test.log
    for more information about the load.
    SCOTT@orcl12c> CREATE TABLE a_table
      2    (rn       NUMBER,
      3     data  NUMBER)
      4  /
    Table created.
    SCOTT@orcl12c> INSERT INTO a_table (rn, data)
      2  SELECT s.rn,
      3         t.COLUMN_VALUE data
      4  FROM   staging s,
      5         TABLE (s.whole_row) t
      6  WHERE  MOD (rn, 2) != 0
      7  /
    17 rows created.
    SCOTT@orcl12c> SELECT * FROM a_table
      2  /
            RN       DATA
             1          1
             1          2
             1          2
             1          3
             1          3
             1         34
             1          4
             1          4
             1          4
             1          5
             1          5
             1          5
             1
             1
             1          5
             3        101
             3        201
    17 rows selected.

  • 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 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..

  • 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 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

  • Read specified line from a text file

    Hi,
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
    Thanks and regards,
    Krt_Malta

    Krt_malta wrote:
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number?

  • How to read a table from a word file, using HWPF

    How can I read a table from a Word file using HWPF?
    I looked in API and Table class doesn't seem to have a constructor... very very strange for me. pls help

    the constructor is HWPFDocument = new HWPFDocument(/*file*/)
    Here is the API for that
    http://poi.apache.org/apidocs/org/apache/poi/hwpf/HWPFDocument.html
    Also here is another link to something that might help you more with tables
    http://www.aspose.com/Community/forums/thread/79182.aspx

  • 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"

  • How do i split content from the text file using tab and spaces...?

    Hi.. Just want to ask help to all the experts. Im new in java and i have this problem on how to split the contents of the text file. ill show you the contents in order to let you see what i mean.
    FileName: COL.txt
    AcctNo AcctName Primary Secondary Status Opendate
    121244 IPI Company Noel Jose Active 12/05/2007
    As you can see the content i want to split it per column.. Please help me

    Jose_Noel wrote:
    Hi prometheuzz,
    What do you mean by one thread...?You created two threads* with the same question in it. That way, people might end up giving you an answer that has already been posted in your other thread: thus wasting that person's time.
    Just don't create multiple threads with the same question please.
    * a thread is a post here at the forum

  • By Java how to delete some lines in a text file containg some character?

    Hello All,
    I am having a text file [Basically It is a Sql File]. its containing some commented lines.
    All i need to do is, By using a java Method I have to delete All the commented lines in That file .....
    For Example if My file is like following.
    /**** Commented By Kannan *********/
    Select * From Employee;
    go
    /******************** Commented by Others ********/
    Select * From DevMembers;
    go
    /*** Ends here **********/
    And the output file would be
    Select * From Employee;
    go
    select * From DevMembers;
    go
    can Anyone Help me in this regards,
    Akram Kannan

    BufferedReader should probably wrap the FileReader if you will be reading line-by-line. Same with the Writer.
    And a simple -
    if (  "/*".equals(record.substring(0,1) ) ... should handle the comment locations bit.
    Message was edited by:
    abillconsl

  • How to read partcicular line from a txt file

    in a text file let there be 50 lines
    while reading the line if the line is having "name" as a string in that line then i have to store the next two consecutive lines in a string as array....
    Similar way and so on......
    How can we do this....

    You need a BufferedReader:
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html
    for example:try {
        BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
        String line;
        while ( (line=br.readLine()) != null ) {
         if (line.indexOf("name") != -1) {
             // Store the next two lines.
             // You will need to call br.readLine() again.
    } catch (IOException x) {
        x.printStackTrace();
    }

  • How to edit/modify a line of a text file using java io

    Hi every body
    I am new 2 java
    I am struck in editing a text file that ends with .dat
    I successfully added,viewed data of the *.dat file.
    but,I cannt edit,delete the lines that i need to do randomly.
    Here is the code i have written.
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.io.RandomAccessFile;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    public class ReadWriteFile {
         String id=null;
         String name=null;
         String dept=null;
         String doj=null;
         String adrss=null;
         public void WriteFile(String Id,String Name,String Dept,String Doj,String Adrss) throws IOException{
              File f=new File("TraineeDetails.dat");
             if(!f.exists()){
             f.createNewFile();
              BufferedWriter bw=new BufferedWriter(new FileWriter("TraineeDetails.dat",true));
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.print("Enter Id : ");
              Id=br.readLine();
              System.out.print("Enter name : ");
              Name=br.readLine();
              System.out.print("Enter dept : ");
              Dept=br.readLine();
              System.out.print("Enter doj : ");
              Doj=br.readLine();
              System.out.print("Enter adrss : ");
              Adrss=br.readLine();
              bw.write(Id+"::"+Name+"::"+Dept+"::"+Doj+"::"+Adrss+":END:");
              bw.flush();
              bw.newLine();
              bw.close();
         public static void main(String[] args) throws IOException {
              ReadWriteFile rwf=new ReadWriteFile();
              String TID = null;
              String TADRSS = null;
              String TDOJ = null;
              String TNAME = null;
              String TDEPT = null;
              rwf.ReadFile(TID,TNAME,TDEPT,TDOJ,TADRSS);
         public void ReadFile(String Id1,String Name1,String Dept1,String Doj1,String Adrss1) throws IOException{
              BufferedReader br = new BufferedReader(new FileReader("TraineeDetails.dat"));
              String s;
               while((s = br.readLine())!= null)
                 // Create string tokenizer
                    StringTokenizer st =new StringTokenizer(s, "::");
                      System.out.println("----------------------------------------------");
                      System.out.println("| Trainee Id: "+st.nextToken()             +"|");
                      System.out.println("| Trainee Name: "+st.nextToken()           +"|");
                      System.out.println("| Trainee Department:"+st.nextToken()      +"|");
                      System.out.println("| Date of Joining: "+st.nextToken()        +"|");
                      System.out.println("| Trainee Address: "+st.nextToken()        +"|\n");
                      System.out.println("----------------------------------------------");
               // Close file reader
               br.close();
    }     and here is the data i have written
    Trainee.dat*
    111::jain::roads::2-2008::Blore:END:
    123::tim::service::1-2000::delhi:END:
    444::faru::civil::3-2200::sanapur:END:
    555::niv::cse::10-2000::gnagar:END:
    999::linda::mech::6-2001::tnagar:END:
    258::yansi::geo::8-2002::rtnagar:END:
    656::hari::garrage::3-1000::uttarahalli:END:
    888::muni::hr::5-2009::ernakulam:END:
    007::bond::spy::2-1972::america:END:
    0123::landy::games::6-2003::hdp:END:
    678::maddy::pumbing::4-1999::dispur:END:

    kalanidhi2u wrote:
    I want to randomly access the file
    But i cannt access itmake it RandomAccessFile... RandomAccessFile
    I edited it
    but i cannt edit the file by using itBoth of these are contradictory.

  • Inserting line in a Text file using java

    Hi,
    I am working on a project in which the some data is required to be stored in a text file. I have lines of data in the file and I read 1 line at a time. So now I need to insert some lines of text in between. How to do this ??
    Now i'm using a temporary file and then after creating the data I replace the original file with the new one. But want to know is there any better way to do that same..?!?!

    Ok.. If I maintain a data in XML format, is it
    possible to insert a node. I'm using Xerces and DOM
    api for handling xml data.
    As a file, XML is just a text file so you insert as you would any file.
    Once parsed to a DOM model then sure you can insert nodes. Just look at the Javadoc for XML Document, Element, Node etc.

Maybe you are looking for