Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9126777
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T07:07:19+00:00 2026-06-17T07:07:19+00:00

I am currently replacing some strings in a line from a text file. The

  • 0

I am currently replacing some strings in a line from a text file. The file has these contents:

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

My code is as follow: The program is just replacing string from specific lines defined in an array. I have to keep the original indentation as they were.

public class ReadFileandReplace {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
        boolean l1;
        int num[] = {1, 2, 3};
        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("C:\\Users\\Antish\\Desktop\\Test_File.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fs));

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

        int count = 1;
        String line = br.readLine();
        while (line != null) {

             l1 = line.contains("\t");
             System.out.println(l1);
            String replaceValue = lineValueMap.get(count);
            if(replaceValue != null) {
                if(l1==true){
                writer1.write("\t"+replaceValue);}
                 writer1.write(replaceValue);
            } else {
                writer1.write(line);
            }
            writer1.write(System.getProperty("line.separator"));
            line = br.readLine();
            count++;
        }
        writer1.flush();
    }
}

I get this output:

output

The indentation for CDCD has been lost and it should start from the original position it was in the original text file.

Can someone guide me how to fix this. 1 Tabspace check in the code work fine but how to check for 2 or more tabspaces.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T07:07:21+00:00Added an answer on June 17, 2026 at 7:07 am

    I would convert the println() statement from string to a char[] array & within a loop I check if the current char is an escape character ‘\t’ (a tab).

    Lets say that all characters till ‘S’ of …

    System.out.println("My method has been accessed"); 
    

    …are tabs, then the value stored in a variable is equal to the number of tabs & afterwards apply those number of tabs. Remember that when you wrote the ‘Test_File’ you pressed spaces instead of pressing tabs you won’t be able to identify how many tabs are there.

    Please compare this code with yours to follow Java conventions.

    CODE:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    /**
     *
     * @author Deathstar
     */
    public class MyC
    { 
    
    public static void main(String[] args)
    {
    
      BufferedReader br = null;
    
      boolean isLineMatched = false;
      int c1 = 0, lineNumArrLength, lineCount = 0;
      int lineNums[] = {1,2};
      char[] toCharArr;
      String sCurrentLine, oldText, addSpaces = "";
      String[] valuesToOverwrite = new String[] {"AB","BC","CD"};
    
        try 
        {
    
          lineNumArrLength = lineNums.length;
    
          br = new BufferedReader(new FileReader("C:\\Users\\jtech\\Documents\\NetBeansProjects\\HelpOthers\\src\\textFiles\\Test_File.txt"));
    
          FileWriter writer1 = new FileWriter("C:\\Users\\jtech\\Desktop\\Test_File1.txt");
    
          for (int i = 0;i < (valuesToOverwrite.length -1) ;i++ ) //Loop 3 Times
          { 
              writer1.append(valuesToOverwrite[i]+System.lineSeparator()+System.lineSeparator());
          }
    
          while ((sCurrentLine = br.readLine()) != null )
          {
              oldText = sCurrentLine; 
              lineCount++;        
              isLineMatched = false;      
              toCharArr = sCurrentLine.toCharArray();
    
              while (c1 < lineNumArrLength) 
              {
                  if (lineCount == lineNums[c1])   
                  {
                    for (int c2 = 0; c2 < toCharArr.length; c2++)
                    {
                        if (toCharArr[c2] == ' ')
                        {
                            addSpaces += " ";
                        }
                    }
                          String newText = sCurrentLine.replace(oldText, addSpaces+valuesToOverwrite[lineCount]);
                          writer1.append(newText+System.lineSeparator());
                          isLineMatched = true;
                          addSpaces = "";
                  } 
                  c1++; 
    
              }
    
              if (isLineMatched == false)
              {
                writer1.append(oldText+System.lineSeparator());
              }
    
              c1 = 0;
          }
    
    
    
    
          writer1.close();
    
    
        } 
        catch (IOException e) 
        {
          e.printStackTrace();
        } 
        finally 
        {
          try 
          {
            if (br != null)
            {
                  br.close();
            }
          } 
          catch (IOException ex) 
          {
            ex.printStackTrace();
          }
        }    
      }        
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am currently replacing some functionality in a twiki page that has been pulling
We are currently replacing our product search from mysql to a SOLR backend. Our
I'm currently adding a new node to an XML file. Since the node has
I have a vbscript that inserts some strings into a database. Often, these strings
I would like to do some text conversion, such as reading in from a
I have a JLabel that needs to display some html-formatted text. However, I want
I've seen some interesting ways to handle strings with Linq: For example, to hide
I am currently writing some framework code that provides a blueprint for services within
Currently, I have the following Python regex: r'^https?://(www.)?domain.com/?(?P<path>.*)/?$' That I'm replacing with: r'/\g<path>/' This
I'm currently attempting to retrieve a list of objects from my database using jQuery.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.