Deathstar
Deathstar

Reputation: 85

Replace lines in File with another string

I have a text file with the following contents:

public class MyC{
public void MyMethod()
{
    System.out.println("My method has been accessed");
    System.out.println("hi");
}
}

I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array

String[] VALUES = new String[] {"AB","BC","CD"};

That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.

Lines which are not in the num[]array have to be written to a new file along with the changes made.

I have this so far.I tried several kind of loops but still it does not work.

public class ReadFileandReplace {

/**
 * @param args
 */
public static void main(String[] args) {



    try {



         int num[] = {3,4,5};

         String[] VALUES = new String[] {"AB","BC","CD"};

         int l = num.length;

         FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(fs));

         LineNumberReader reader = new LineNumberReader(br);

         FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");

         String line;
         int count =0;

         line = br.readLine();
         count++;

         while(line!=null){
              System.out.println(count+": "+line);
              line = br.readLine();
              count++;

              int i=0;
                  if(count==num[i]){
                      int j=0;;
                    System.out.println(count);
                    String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
                    j++;
                                            writer1.write(newtext);
                  }
                  i++;
                  writer1.append(line);
              }


    writer1.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    } finally {
    }

}


}

The expected output should look like this:

public class MyC{
AB
BC
    CD
    Sys.out.println("hi");
}
}

When I run the code, all lines appear on the same line.

Upvotes: 1

Views: 8394

Answers (4)

Renjith
Renjith

Reputation: 3274

Try This

package src;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

public class MainTest {


    static int i ;

    public static void main(String[] arg)
    {
        try {



             int num[] = {3,4,5};

             String[] VALUES = new String[] {"AB","BC","CD"};

             FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
             BufferedReader br = new BufferedReader(new InputStreamReader(fs));

             FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");

             String line;
             Integer count =0;

             line = br.readLine();
             count++;

             while(line!=null){


                 for(int index =0;index<num.length;index++){
                     if(count == num[index]){
                         line = VALUES[index];
                     }
                 }


                 writer1.write(line+System.getProperty("line.separator"));

                 line = br.readLine();

                 count++;


                 }


        writer1.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

}
}

Upvotes: 0

vels4j
vels4j

Reputation: 11298

You've done almost, I've updated your code with a map. Check this

int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};

HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
    lineValueMap.put(num[i],values[i]);
}


FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));

FileWriter writer1 = new FileWriter("test1.txt");

int count = 1;
String line = br.readLine();
while (line != null) {
    String replaceValue = lineValueMap.get(count);
    if(replaceValue != null) {
        writer1.write(replaceValue);
    } else {
        writer1.write(line);
    }
    writer1.write(System.getProperty("line.separator"));
    line = br.readLine();
    count++;
}
writer1.flush();

Upvotes: 2

user684934
user684934

Reputation:

You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))

Upvotes: 2

Amit
Amit

Reputation: 388

you have not appended end line character. writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to: writer1.append(line).append("\n");

Upvotes: 0

Related Questions