4

I've got a text file called log.txt. It's got the following data

1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
2,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg

The numbers before the first comma are indexes that specify each item.

What I want to do is to read the file and then replace one part of the string(e.g. textFiles/a.txt) in a given line with another value(e.g. something/bob.txt).

This is what I have so far:

    File log= new File("log.txt");
                    String search = "1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg;
                    //file reading
                    FileReader fr = new FileReader(log);
                    String s;
                    try (BufferedReader br = new BufferedReader(fr)) {
                        
                        while ((s = br.readLine()) != null) {
                            if (s.equals(search)) {
                                //not sure what to do here
                            }
                        }
                    }
3
  • if you are open to use perl: perlpie.com Commented May 5, 2014 at 6:33
  • If your format for storing strings is the same for all intances, what you can do is :- Search for that particular string, create a string array by using delimiter which is ',' in your case, replace your string at that particular index in that array, and replace back in your text file. This is one way. Not so efficient but may solve your purpose Commented May 5, 2014 at 6:37
  • try s = s.replaceAll("(?<=\\d{4}\\,)(.*)(?=\\,images)", "something/bob.txt"); Commented May 5, 2014 at 6:45

4 Answers 4

12

You could create a string of total file content and replace all the occurrence in the string and write to that file again.

You could something like this:

File log= new File("log.txt");
String search = "textFiles/a.txt";
String replace = "replaceText/b.txt";

try{
    FileReader fr = new FileReader(log);
    String s;
    String totalStr = "";
    try (BufferedReader br = new BufferedReader(fr)) {

        while ((s = br.readLine()) != null) {
            totalStr += s;
        }
        totalStr = totalStr.replaceAll(search, replace);
        FileWriter fw = new FileWriter(log);
    fw.write(totalStr);
    fw.close();
    }
}catch(Exception e){
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Solution removes line breaks if there are any
The entire file must be read to memory. Can be a problem if the file is too big.
3

One approach would be to use String.replaceAll():

File log= new File("log.txt");
String search = "textFiles/a\\.txt";  // <- changed to work with String.replaceAll()
String replacement = "something/bob.txt";
//file reading
FileReader fr = new FileReader(log);
String s;
try {
    BufferedReader br = new BufferedReader(fr);

    while ((s = br.readLine()) != null) {
        s.replaceAll(search, replacement);
        // do something with the resulting line
    }
}

You could also use regular expressions, or String.indexOf() to find where in a line your search string appears.

2 Comments

once it is replaced how to i write it back to the same file?
You shouldn't write back into the same file while you are reading it. You could write a new file, and then at the end of the process delete the file you read and rename the new one.
1

Solution with Java Files and Stream

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

private static void replaceAll(String filePath, String text, String replacement) {
        
        Path path = Paths.get(filePath);
        // Get all the lines
        try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
            // Do the replace operation
            List<String> list = stream.map(line -> line.replace(text, replacement)).collect(Collectors.toList());
            // Write the content back
            Files.write(path, list, StandardCharsets.UTF_8);
        } catch (IOException e) {
            LOG.error("IOException for : " + filePath, e);
            e.printStackTrace();
        }
    }

Usage

replaceAll("test.txt", "original text", "new text");

Comments

-3

A very simple solution would be to use:

s = s.replace( "textFiles/a.txt", "something/bob.txt" );

To replace all occurrences, use replaceAll shown in another proposal, where a regular expression is used - take care to escape all magic characters, as indicated there.

Comments

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.