Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: JAVA = Replace a line in a text file

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question JAVA = Replace a line in a text file

    I want to create a program that will replace some of the text within a text file, however when I attempt to do so it deletes the rest of the file so I'm left with just the replaced line.

    For example if i want to change the fourth record from e to d it deletes items within the file.

    Text File before
    1 a
    2 b
    3 c
    4 e

    Text File after
    4 d

    Can anyone help??

    //package org.kodejava.example.io;
     
    import java.io.*;
    import java.util.*;
     
    public class LineNumberReaderExample {
        public static void main(String[] args) throws Exception {               
            File file = null;
            FileReader fr = null;
            LineNumberReader lnr = null;
     
            try {
                Scanner input=new Scanner(System.in);
                System.out.print("Enter record to edit ");
                String word=input.next();
                file = new File("file.txt");
                fr = new FileReader(file);            
                lnr = new LineNumberReader(fr);
                String line = "";
     
                while ((line = lnr.readLine()) != null) {
                    if(line.startsWith(word)){
     
                    System.out.println("Line Number " + lnr.getLineNumber() + ": " + line);
                    String[] st = line.split(" ");
                    String date = st[0];
                    String event = st[1];
     
                    System.out.print("Replace With: ");
                    String newtext=input.next();
                    FileWriter writer = new FileWriter("file.txt");
                    writer.write(line.replace(event, newtext));
                    writer.close();
                    }     
     
                }
            } 
           finally {
                if (fr != null) {
                    fr.close();
                }
                if (lnr != null) {
                    lnr.close();
                }
            }
        }
    }

    Once I get this code working I can then save dates and events to the text file.


  2. #2
    Administrator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,848
    Thanks
    64
    Thanked 2,645 Times in 2,615 Posts

    Default Re: JAVA = Replace a line in a text file

    To change the middle of a file, you need to copy everything before the changed area to an output file, then write the changed part and then copy everything after the changed area to the output file.
    There is a case when the new data EXACTLY byte for byte replaces the old data where you could use the RandomAccessFile class to write the new data over the top of the old data.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Re: JAVA = Replace a line in a text file

    The tutorial I'm basing this on does replace the text, I can's see what I've done differently in mine apart from allowing the user to imput what sections they wish to replace.

    import java.io.*;
     
    public class BTest
        {
         public static void main(String args[])
             {
             try
                 {
                 File file = new File("file.txt");
                 BufferedReader reader = new BufferedReader(new FileReader(file));
                 String line = "", oldtext = "";
                 while((line = reader.readLine()) != null)
                     {
                     oldtext += line + "\r\n";
                 }
                 reader.close();
                 // replace a word in a file
                 //String newtext = oldtext.replaceAll("drink", "Love");
     
                 //To replace a line in a file
                 String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
     
                 FileWriter writer = new FileWriter("file.txt");
                 writer.write(newtext);writer.close();
             }
             catch (IOException ioe)
                 {
                 ioe.printStackTrace();
             }
         }
    }

    Java sample code - Replace a line or word in a file - Source code examples

  4. #4
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA = Replace a line in a text file

    I have followed a tutorial, which only changes the line of the text, the only difference I made was that users input the search and replace criteria.

    Replace a line or word in a file
     
    import java.io.*;
     
    public class BTest
        {
         public static void main(String args[])
             {
             try
                 {
                 File file = new File("file.txt");
                 BufferedReader reader = new BufferedReader(new FileReader(file));
                 String line = "", oldtext = "";
                 while((line = reader.readLine()) != null)
                     {
                     oldtext += line + "\r\n";
                 }
                 reader.close();
                 // replace a word in a file
                 //String newtext = oldtext.replaceAll("drink", "Love");
     
                 //To replace a line in a file
                 String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
     
                 FileWriter writer = new FileWriter("file.txt");
                 writer.write(newtext);writer.close();
             }
             catch (IOException ioe)
                 {
                 ioe.printStackTrace();
             }
         }
    }
     
    /*
    file.txt
    I drink Java
    I sleep Java
    This is test string 1
    This is test string 20000
    */

    Tutorial - Java sample code - Replace a line or word in a file - Source code examples

  5. #5
    Administrator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,848
    Thanks
    64
    Thanked 2,645 Times in 2,615 Posts

    Default Re: JAVA = Replace a line in a text file

    Can you post the contents of the input file and the contents of the file that is written out?

    For testing you should use different files for input and output.

  6. #6
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA = Replace a line in a text file

    Sorry I've changed my method of saving now. Ignore this thread

  7. #7
    Junior Member
    Join Date
    Nov 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA = Replace a line in a text file

    Could you please upload your final codes? Thanks

  8. #8
    Moderators
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    7,448
    My Mood
    Mellow
    Thanks
    288
    Thanked 899 Times in 879 Posts

    Default Re: JAVA = Replace a line in a text file

    Probably not, since this topic is several months old. Start a new topic if you need help to solve a similar problem.

Similar Threads

  1. Replies: 0
    Last Post: October 29th, 2012, 01:17 AM
  2. How to plot line graph using jfreechart reading from text file
    By priti in forum Java Theory & Questions
    Replies: 9
    Last Post: March 31st, 2012, 02:39 PM
  3. how to plot the line graph using jfreechart reading from text file
    By priti in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 31st, 2012, 07:53 AM
  4. Writing to a specific line in a text file
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 7th, 2011, 09:11 PM
  5. How to Read a file line by line using BufferedReader?
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: May 19th, 2008, 07:32 AM

Tags for this Thread