Replacing word in a text  file...in java

hello;
could anyone plz help me in writing a program in java that will replace a specific word with a specific word?Though i can read and write to a file. I need it urgently....plz help me...
regards
[email protected]

public class wordReplace {
public static void main(String [] args)
String oldStr = "They can do it easily..." ;
String newStr = oldStr.replaceAll("They", "You");
System.out.println(newStr);
}

Similar Messages

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

  • What is the best way of replacing words in a text file ?

    i want to read in a text file and when i come across a certain word, i want to change it to something else. Whats the best way to do this ?
    If i read in a line at a time, how would i only replace one word and not the rest of the line ?
    thanks

    thanks it works !!! But i wrote the contents to a new file.
    How do i overwrite the same file ? I put the the input and output file as the same location but it overwrites the original file with a blank one.
    i guess i have to write into another buffer and read all lines first before overwriting the file right ? how should i do that ?
    also, i only want to overwrite the file ONLY if applies replaceAll method, otherwise if no replacing takes place i dont want to keep updating the file everytime.

  • Replace/cut part of words from a text file.

    Hello Hello everyone, I have a quick question. I have my text file that contains also words like ... let's say abc1, abc2 and so on, and I need to cut the c from the word, I need ab1, ab2.
    Here is what I have started:
    import java.util.*;
    import java.io.*;
    public class test
            Vector<String> x = new Vector<String>();
    public mergefiles() throws IOException
            readAdd("test.txt");
            write("testout.txt");    
    private void readAdd(String name) throws IOException
            BufferedReader reader = new BufferedReader(new FileReader(name));
            String line,all=new String();
            while ((line = reader.readLine ()) != null)
                    all+=line+'\n';
            reader.close ();
            int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   String between=all.substring(posX+3,all.length());
                   StringTokenizer st=new StringTokenizer(between," \n");
    private void write(String name) throws IOException
            BufferedWriter writer = new BufferedWriter(new FileWriter(name));
            String s=new String();
             if (x.size()>0)
                  s+="X"+'\n';
             s+='\n';
             writer.write(s);
            writer.close();
    public static void main(String[] args) throws IOException
            new test();
    }I am new to Java and I would really appreciate if you would be patient with me.
    Thank you!

    I have tried in readAdd method something like:
    int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   string.replace("ab1","abc1");
              }     but still doesn't work, and this is not a really good ideea, in case that I have to replace 1000 of abci ...I should use a for in my write method:
    String[] s=new String[2];
    for(int i=0;i<word.length;i++)
                   BufferedWriter writer = new BufferedWriter(new FileWriter(testout.substring(0, testout.lastIndexOf("."))+(i+1)+".txt"));
                       writer.write(s);
              writer.close();
    But I not really sure if this is ok! Right now nothing is working
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help to add the words in a text file to an arraylist

    I am new to java and I really need some help for my project.I want to add the words of a text file to an arraylist. The text file consist of words and the following set of punctuation marks {, . ; : } and spaces.
    thanks in advance :-)

    I/O: [http://java.sun.com/docs/books/tutorial/essential/io/index.html]
    lists and other collections: [http://java.sun.com/docs/books/tutorial/collections/index.html]

  • To get  a  word in the text  file

    Hi,
    I m beginner to java.
    HOw i get a word in the text file.
    I used this code, it is only display the all sentence which are available in the text file.
    But , I need to print particular word (if it is available in that text file)
    package com.beryl;
    import java.io.*;
    class FileReadTest {
    public static void main (String[] args) {
         FileReadTest f = new FileReadTest();
    f.readMyFile();
    void readMyFile() {
         BufferedReader dis =null;
    String record = null;
    int recCount = 0;
    try {
    File f = new File("E:/hello/abc.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis
    = new BufferedReader(new InputStreamReader(bis));
    while ( (record=dis.readLine()) != null ) {
    recCount++;
    System.out.println(recCount + ": " + record);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
         try {
    dis.close();
         } catch (IOException ioe) {
    Thanks & Regards,
    kumar

    I used this code, it is only display the all
    sentence which are available in the text file.
    But , I need to print particular word (if it
    is available in that text file)if
    String.indexOf()

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

  • Word count in text file

    Hi,
    I am trying to count word in my text file by using the Java code. Even though i am error in the code and don't know what sintaks to use. For example:
    I have
    school 4
    bus 3
    student 5
    in a.txt
    Another text file
    bus 2
    school 2
    in b.txt
    I want to display in new text file: c.txt
    school 6 4 : a.txt 2 : b.txt
    bus 5 3 : a.txt 2 : b.txt
    student 5 5 : a.txt
    Could you please advise,what sintak that i could use??
    Thanks you..

    Use StringTokenizer object and HashMap Object
    example
    String str = (your text readed from file A)
    StringTokinzed token = new StringTokinzed(str);
    while (token.hasMoreTokens()) {
    String word = token.nextToken()
    Integer i = (Integer) hashmap.get(word);
    if (i==null) {
    i = new Integer(1);
    }else
    i++;
    hashmap.put(word,i);
    same code for B file
    iterate through the hasmap and print all word with the count

  • Replace a string within text file to another string

    hi everybody
    i wich to replace some word writed in text file to another word,,,,for example i want to replace all word when the word is "SOLARIS" to "solaris" .
    anyone have an idea to resolve this prob via command or script,plz respond me.
    thanks

    To elaborate on alan.pae's response:
    sed 's/SOLARIS/solaris/g' oldfilename > newfilename
    -systemstate

  • 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 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 get the source code of an HTML page in Text file Through java?

    How to get the source code of an HTML page in Text file Through java?
    I am coding an application.one module of that application is given below:
    The first part of the application is to connect our application to the existing HTML form.
    This module would make a connection with the HTML page. The HTML page contains the coding for the Form with various elements. The form may be a simple form with one or two fields or a complex one like the form for registering for a new Bank Account or new email account.
    The module will first connect through the HTML page and will fetch the HTML code into a Text File so that the code can be further processed.
    Could any body provide coding hint for that

    You're welcome. How about awarding them duke stars?
    edit: cheers!

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

  • Reading words from a text file

    I have written code to store words in a text file. they appear in the text file as shown below.
    word1
    word2
    word3
    etc.
    I want to read each word individually and store them in an array. Im trying to do it using a BufferedReader but it doesn't seem to work. The code for reading the words is shown below. Any suggestions would be appreciated.
    try
    FileReader reader = new FileReader("words.txt");
    BufferedReader bReader = new BufferedReader(reader);
    ArrayList words = new ArrayList();
    String line;
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    bReader.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    }

    I think your code is wrong, because it Read two time from file,
    your code like....
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    you have to change the above code like
    while((line = bReader.readLine()) != null)
    words.add(line);
    NOW ITS WORKING FINE,...........

  • Read Text file using Java Script

    Hi,
    I am trying to read a text file using Java Script within the webroot of MII as .HTML file. I have provided the path as below but where I am not able to open the file. Any clue to provide the relative path or any changes required on the below path ?
    var FileOpener = new ActiveXObject("Scripting.FileSystemObject");
    var FilePointer = FileOpener.OpenTextFile("E:\\usr\\sap\\MID\\J00\\j2ee\\cluster\\apps\\sap.com\\xapps~xmii~ear\\servlet_jsp\\XMII\\root\\CM\\OCTAL\\TestTV\\Test.txt", 1, true);
    FileContents = FilePointer.ReadAll(); // we can use FilePointer.ReadAll() to read all the lines
    The Error Log shows as :
    Path not found
    Regards,
    Mohamed

    Hi Mohamed,
    I tried above code after importing JQuery Library through script Tag. It worked for me . Pls check.
    Note : You can place Jquery1.xx.xx.js file in the same folder where you saved this IRPT/HTML file.
    <HTML>
    <HEAD>
        <TITLE>Your Title Here</TITLE>
        <SCRIPT type="text/javascript" src="jquery-1.9.1.js"></SCRIPT>
        <script language="javascript">
    function Read()
    $.get( "http://ldcimfb.wdf.sap.corp:50100/XMII/CM/Regression_15.0/CrossTab.txt", function( data ) {
      $(".result").html(data);
      alert(data);
    // The file content is available in this variable "data"
    </script>
    </HEAD>
    <BODY onLoad="Read()">
    </BODY>
    </HTML>

Maybe you are looking for