Aashish Manaktala
Aashish Manaktala

Reputation: 3

How to replace a string from a file?

I have just started programming and I am stuck while creating a basic File I/O program in java.

The use case: I want to check for a string in a file and append a string in the same line. E.G. The file contents are as follows :

hostname=localhost
port=192

So, I want my program to look for hostname string in the above file and replace localhost with what ever value I pass to it.

I am able to get the file and pass the contents to a temporary file , but not sure how to manipulate strings in the file. Any help is highly appreciated.

Upvotes: 0

Views: 2699

Answers (3)

A4L
A4L

Reputation: 17595

Here are two ways (basic without any error/exception handling and passing target and replacement as arguments) how you can do it.

If your file stores key/value pairs than the best way is to user java.util.Properties

public class ReplaceInFile {

    private final static String src = "test.txt";
    private final static String dst_str = "test_new_str.txt";
    private final static String dst_prop = "test_new_prop.txt";

    public static void main(String[] args) throws IOException {
        usingStringOperations();
        usingProperties();
    }

    private static void usingProperties() throws IOException {
        File srcFile = new File(src);
        FileInputStream fis = new FileInputStream(srcFile);
        Properties properties = new Properties();
        properties.load(fis);
        fis.close();
        if(properties.getProperty("hostname") != null) {
            properties.setProperty("hostname", "127.0.0.1");
            FileOutputStream fos = new FileOutputStream(dst_prop);
            properties.store(fos, "Using java.util.Properties");
            fos.close();
        }
    }

    private static void usingStringOperations() throws IOException {
        File srcFile = new File(src);
        FileInputStream fis = new FileInputStream(srcFile);
        int len = fis.available();
        if(len > 0) {
            byte[] fileBytes = new byte[len];
            fis.read(fileBytes, 0, len);
            fis.close();
            String strContent = new String(fileBytes);
            int i = strContent.indexOf("localhost");
            if(i != -1) {
                String newStrContent = strContent.substring(0, i) + 
                        "127.0.0.1" +
                        strContent.substring(i + "localhost".length(), strContent.length());
                FileOutputStream fos = new FileOutputStream(dst_str);
                fos.write(newStrContent.getBytes());
                fos.close();    
            }
        }
    }
}

Upvotes: 0

Aditi
Aditi

Reputation: 1188

You will need to use replace, concat etc. methods. Try some code and post if you get stuck!

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html

Upvotes: 0

Bastien Jansen
Bastien Jansen

Reputation: 8846

You could try String.replace():

String replacement = "you-other-host";

// Read your file line by line...
line = line.replace("localhost", replacement);
// and write the modified line to your temporary file

Upvotes: 1

Related Questions