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.

Similar Messages

  • 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

  • How to read the last line in a text file using text_io?? please help

    Dear all
    I made a procedure that append text into a text file on the operating system.
    the text file grows rapidly. It contains now about 200,000 line . I need to read the last line only . In other wprds i need to go direct to the last line to read some values. Is it possible??
    Please help

    Hello,
    If you know the number of the line you want to read, I can sugget you to use the MORE dos command or the TAIL unix command that redirect to a temporary text file
    Example to create a file that contains the 200010th last lines :
    (Client)Host( 'MORE the_file_name.txt +200010 > small_file.txt') ;So you have only to read the small file with the TEXT_IO functions.
    Francois

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

  • How to replace a line ina text file using java?

    Hi ALL,
    Does anybody know how to replace a line in a text file uisng java.

    use this thing:
    http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
    open the file,
    read its contents, replace the text you need in the contents, set the contents back into the file.
    it takes care of the IO for you.

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

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • How to convert a HTML files into a text file using Java

    Hi guys...!
    I was wondering if there is a way to convert a HTML file into a text file using java programing language. Likewise I would also like to know if there is a way to convert any type of file (excel, power point, and word) into text using java.
    By the way, I really appreciated the help that you guys gave me on my previous topic on how to extract tests from a pdf file.
    Thank you....

    HTML files are already text files. What do you mean you want to convert them?
    I think if you search the web, you can find things for converting those MS Office files to text (or extracting text from them, as I assume you mean).

  • How to edit the existing data in the XML file from java programming.

    Hi all
    i am able to create XML file with the sample data as below from java programming.
    i need sample code on how to edit the existing data in the XML file?
    for example
    <?xml version="1.0"?>
       <mydata>
               <data1>
                         <key1>467</key1>
                        <name1>Paul</name1>
                        <id1>123</id1>
              </data1>
              <data2>
                         <key2>467</key2>
                        <name2>Paul</name2>
                        <id2>123</id2>
              </data2>
        </mydata>
    i am able to insert the data in the XML.
    now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
    Regards
    Sunil
    [points will be always rewardable]

    hi
    u need a parser or validate the xml file for to read the xml file from java coding u need for this
    xml4j.jar u can download this file  from here
    http://www.alphaworks.ibm.com/tech/xml4j
    or we can use the SAX(simple API for XML)
    some sample applications for this
    http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
    http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
    http://www.xml-training-guide.com/e-xml44.html
    let me know u need any other info
    bvr

  • How to write an xml Document to a flat file using JAVA....

    Can any one help me out.....
    How to write a XML Document to the current filesystem using JAVA....
    without using com.sun.xml.tree.*....
    Document xmlDoc;
         Node rows = (Node) xmlDoc.createElement("ROWS");
    xmlDoc.appendChild(rows);
    and i have to write this xmlDoc to a file called(abc.xml) for further use...

    Have you considered using JDOM? ( www.jdom.org )
    The XMLOutputter class can write the Document to a file. ( The Document however will be an org.jdom.Document object ).
    If you are weary of a new API, you could just create a new File object called abc.xml and stream the data from the XML Document you have to this new File object.

  • Want to know how to check for new line character in text file

    Hi All,
    I`m trying to read data from text file. However I`m not sure whether the data is in 1st line or nth line. Now I`m trying to read the text from the readline. But if text is "" and not NULL then my code fails. So I want to know how to check for new line character and go to next line to find the data. Please help.
    Thanks
    static int readandwriteFile(Logger logger,String filepath){
              BufferedWriter out = null;
              BufferedReader in = null;
              File fr = null;
              int get_count = 0;
              try     {
              if(new File(filepath).exists())
              fr= new File(filepath);
                        System.out.println("FileName: "+fr);
                   if(fr != null){
    in = new BufferedReader(new FileReader(fr));
                             String text = in.readLine();
                             if(text != null){
                             get_count = Integer.parseInt(text);
                             in.close();
                             else{
                                  get_count = 0;
         else{                    
    out = new BufferedWriter(new FileWriter(filepath));
         out.write("0");
                out.close();
                   }          //Reading of the row count file ended.
              catch(Exception e) {
                   e.printStackTrace();
              finally {
                   try{               if (in != null) {
                             in.close();
              if (out != null) {
                             out.close();
              catch(Exception e) {
                        e.printStackTrace();
              return get_count;
         }

    You are calling the readline() only once which means you are reading only the first line from the file...
    Use a loop (Do-While preferably)
    do{
    //your code
    }while(text == "")

  • How to write after a line in a text file

    i need to write a string into a text file, after a particular line that i need to search.
    The line to serch and the line to write are two String types.
    String line_to_search="<first";
    String line_to_write="<second>";

    I found a way to make that but now i have another problem, the system write the String in the file but with a space. In particular in the code a want to write the string in the third line
    The code is
    <%@ page import="java.io.*" %>
    <%
    String value ="Anthony";
    RandomAccessFile file = null;
    file = new RandomAccessFile ("G:\\rrr.txt", "rw");
    String aaa=file.readLine();
    String aaa2=file.readLine();
    file.writeChars(value);
    %>
    The rrr file is before:
    Hello
    my name is
    and after the rr file is
    Hello
    my name is
    A n t h o n y

  • How can i delete a UserName  from a text file using Strings or io.

    hi i m trainee
    i have been assigned to make java program which deletes a UserName and
    his Passwor from a Text File
    i m unable to do it using the code below
    plz help
    do reply
      import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java .applet.*;
    import java.io.*;
    class Del extends JFrame  implements ActionListener
         String s2;
         JTextField CWDMUserDText = new JTextField();
         JButton CWDMSecDelButton = new JButton("DELETE");
         JLabel CWDMUserLabel = new JLabel("USER NAME");
         JPasswordField CWDMPassDText = new JPasswordField();
         JLabel CWDMPassLabel = new JLabel("PASSWORD");
         //String user,pass;
         /* CONSTRUCTOR*/
              Del()
                   Container contentPane=getContentPane();
                   contentPane.setLayout(null);
                  setLocation(400,200);
                   contentPane.add(CWDMUserDText);
                   contentPane.add(CWDMSecDelButton);
                   contentPane.add(CWDMUserLabel);
                   contentPane.add(CWDMPassDText);
                   contentPane.add(CWDMPassLabel);
                  CWDMUserLabel.setBounds(20,70,100,25);
                  CWDMPassLabel.setBounds(20,100,100,25);
                   CWDMUserDText.setBounds(150,70,100,25);
                   CWDMPassDText.setBounds(150,100,100,25);
                   CWDMSecDelButton.setBounds(80,135,100,25);
                   CWDMUserDText.addActionListener(this);
                   CWDMPassDText.addActionListener(this);
                   CWDMSecDelButton.addActionListener(this);
                   contentPane.setBackground(Color.CYAN);
                   setVisible(true);
                   setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent ae)
                  if(ae.getSource()==CWDMSecDelButton)
         //             user = CWDMUserDText.getText();
         //          pass = CWDMPassDText.getText();
         //          showarr();
                   s2 = CWDMUserDText.getText();
                   CWDMUserDText.setText("");
                   CWDMPassDText.setText("");
                   DelUser(s2);
              public static void main(String args[])
                   Del myframe1= new Del();
                   myframe1.setSize(300,200);
                   myframe1.setVisible(true);
              public void DelUser(String s)
                   //int a;
                   try
                        FileReader fr = new FileReader("file.txt");
                        BufferedReader br = new BufferedReader(fr);
                       String s1;
                       int a;
                       int len = s.length();
                       System.out.println(len);
                       //s2 = CWDMUserDText.getText();
                        while ((s1=br.readLine()) !=null)
                             if((a=s1.indexOf(s))>0 && (a=s1.indexOf(s))!=0)
                                  System.out.println(a);
                        fr.close();
                   catch(FileNotFoundException e)
                        System.out.println("exception occured");
                   catch(IOException e)
                        System.out.println("io");
         }

    Some tips:
    1) If you are adding or deleting stuff from a text file you need to write a new, modified file and then, optionally, do something like:
    rename the old file to whatever.bak or the like.
    rename the new file to the old.
    2) Don't depend on System.out so much on a GUI application. For example if you get an exception use javax.swing.JOptionPane to display an alert (and show the message from the exception). You can write the stack trace to System.out if you want.
    3) Don't muck about with calculating bounds for screen objects, let a layout manager sort it out. I like BoxLayoutManager for most things like this.
    4) For bonus points do your IO in a separate Thread. Generally you don't want anything happening in an actionPerformed method which significantly delays it's return. The method should launch a new Thread to do the job, and disable the button until the Thread finishes.

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

Maybe you are looking for

  • Premiere elements has encountered an error.  [..\..\Src\Core\Preferences.cpp-338] (while launching video editor)

    Getting an error while launching Video Editor (either New project or Existing project). However i can launch "Organizer" with no issue. windows 7 -64bit Core i7 Premiere elements has encountered an error.  [..\..\Src\Core\Preferences.cpp-338] then -R

  • IPhone doesn't charge when it's turned on

    I got a slot for iOS 7 from a friend a month or so ago. A couple of days ago, it randomly wouldn't charge when it was on. It has slowly gotten progressively worse. It now only charges when it's off.  When it turns on, all I can do is let it die and l

  • PDF Search function

    I had 2249 pages of old military base newspapers scanned onto a DVD, into folders by years and then by weeks. The company that scanned then said the DVD did not have enough memory on 1DVD  for the seach function to work. now that i have the DVD can i

  • HD video proportions to iBA Media Page

    HD video proportions to iBA Media Page I need to hire a video for use as full-screen on the Media Page in iBA. The video i've selected is in HD format. When i insert the low res test version from the library it works fine but appears with black bars

  • Portal

    Hi, Is it possible to implement vendor neutral portal? I need to maintain a weblogic portal. It's totally locked in weblogic since it uses jpf, netui, etc.. what's the best approach to avoid vendor specifics. Thanks