kaboom
kaboom

Reputation: 833

StringBuffer replace method doesn't work

I want to read a text file in the same folder with my java program. I have a readFile() that is used to read the content of the file line by line. And then the setName() will replace a part of the content. I compile the program and run without error. But the file's content doesn't change at all.

Thank you

public StringBuffer readFile(){ //read file line by line
        URL url = getClass().getResource("test.txt");
        File f = new File(url.getPath());
        StringBuffer sb = new StringBuffer();
        String textinLine;

        try {
            FileInputStream fs = new FileInputStream(f);
            InputStreamReader in = new InputStreamReader(fs);
            BufferedReader br = new BufferedReader(in);

         while (true){
                textinLine = br.readLine();
                if (textinLine == null) break;
                sb.append(textinLine);
            }
            fs.close();
            in.close();
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb;

    }

    public void setName(String newName){
        StringBuffer sb = readFile();       
        int pos = sb.indexOf("UserName=");
        sb.replace(pos, pos+newName.length(), newName);
    }

Upvotes: 1

Views: 418

Answers (2)

CloudyMarble
CloudyMarble

Reputation: 37566

You have to write back to the file so it gets changed but your not changing the content of the StringBuffer, you are reading it only. once you change the content you need to write the new content to the file like:

try{
        FileWriter fwriter = new FileWriter(YourFile);
        BufferedWriter bwriter = new BufferedWriter(fwriter);
        bwriter.write(sb.toString());
        bwriter.close();
     }
    catch (Exception e){
          e.printStackTrace();
     }

Upvotes: 1

mcalex
mcalex

Reputation: 6778

You don't change the content of the file, you change the content of the StringBuffer. If you have a look at your StringBuffer (System.out.println(sb.ToString())) before and after the sb.replace method, you will see where changes are being made

Upvotes: 0

Related Questions