vendredi 18 mai 2018

How to use conditional statement or contains method in a text file?

I have a java program that can read multiple files and replace values accordingly. However, I am struggling to apply a condition to it and apply the changes only when a certain condition is met. For example, if the file contains this specific character ':20:' then apply the changes otherwise leave the text file as it is. The problem here is, since I don't have fields to look for to apply the condition accordingly I don't know how these can be applied to such a text file which contains just data like : (12345555555) 233344 100 :20:aaa.

I also looked at using the contains() method to look into the file to find the value I want then apply the changes but couldn't make it work.

public class TextFm 
{
    public static void main(String[] args)
    {
        File folder = new File("C:\\tmp");
        File[] listOfFiles = folder.listFiles();
        for(File file : listOfFiles) 
        {
            replaceText(file);
        }
    }

    public static void replaceText(File file) 
    {

        try 
        {
            BufferedReader reader = new BufferedReader(new FileReader(file));

            String line = "", oldtext = "";
            while ((line = reader.readLine()) != null) 
            {

                oldtext = oldtext + line + System.lineSeparator();
            }
            reader.close();


            String replacedtext = oldtext.replaceAll("100", "200");


            FileWriter writer = new FileWriter(file);
            writer.write(replacedtext);

            writer.close();

            System.out.println("Done");

        } catch (IOException ioe) 

        {
            ioe.printStackTrace();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire