Search code examples
javareplacestringbuffer

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);
    }

Solution

  • 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();
         }