-1

I would like to write to a file after a set of characters. For example, if I want to write xyz into a file test.txt which contains string hello world. I want write after the letter w. The output should be hello wxyzorld in the file.

How do it do it? Using a FileWriter and BufferedWriter I can write to a file but not at a certain position. Could you help me if there is anyway I can do it?

2
  • 2
    Might be related: stackoverflow.com/questions/28913543/… Commented Oct 17, 2016 at 14:36
  • 3
    HI Aravind! Can you show us the code that you have tried to write so far? From there we can guide you to a solution. You will have better success getting answers to your questions when you show your existing work. Commented Oct 17, 2016 at 15:26

1 Answer 1

1
public static void main(String[] args) {
    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("/path/to/test.txt")));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        int offset = 7;

        while((line = bufferedReader.readLine()) != null) {
                for(int i=0; i<line.length(); i++) {
                    if(i == offset) {
                        stringBuilder.append("xyz" + line.charAt(i));
                    } else if(i == line.length()-1) {
                        stringBuilder.append(line.charAt(i) +"\n");
                    } else {
                        stringBuilder.append(line.charAt(i));
                    }
                }
        }

        System.out.println(stringBuilder);
        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

Something like this perhaps? You can append the rest of the lines accordingly to your StringBuilder.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response. I have use the method that you gave and the code works for me. Thanks
You can mark this as the correct answer if it worked for you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.