0

Hello!

I'm new to this site and fairly new to Java, I've tried creating a program that takes a file as input and edits specific substrings in said file, compiles without problems but the file remains unchanged.

import java.io.*;

public class Uppg10_OH  {
    static class MinHistoria  {
        private String namnInfil;
        private String gammaltNamn;
        private String nyttNamn;
        
        public MinHistoria(String inFilNamn, String gNamn, String nNamn) {
        
            namnInfil       = inFilNamn;
            gammaltNamn     = gNamn;
            nyttNamn        = nNamn;
        }

        public void transformera() throws IOException {
    
            try {
             
                FileInputStream stream = new FileInputStream("C:\\test.txt");
                DataInputStream in = new DataInputStream(stream);
                BufferedReader br = new BufferedReader( new InputStreamReader(in));
            
                String stringRad;
                while ((stringRad = br.readLine()) != null) {
                    if (stringRad.contains(gammaltNamn)) {
                        stringRad.replaceAll(gammaltNamn, nyttNamn);
                    }
                
                }
                in.close();
                br.close();
                
            }   
            catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
        
        public static void main (String args[]) throws IOException {
                  MinHistoria mh = new MinHistoria("C:\\test.txt", "cat", "dog");
                  mh.transformera();
        }
    }
    
}

I'm not quite sure where the problem lies, any help would be greatly appreciated!

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by morred
0

I would like to save it in a different file, haven't yet gotten quite that far.
Should have been clear on this, sorry!

0

You read in the data, change it in memory, then exit. Until you write the code to write the changed data to a file you will not see any changes.
You can check your code so far by printing stringRad at line 29

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.