Search code examples
javafileprintwriter

PrintWriter writes blank file


I want to change the score of the user, but instead of overwriting the file with new scores, it just makes an empty file. The lines are written like this: "username-password-wins-losses-ties"

try {
        BufferedReader br = new BufferedReader(new FileReader("users.txt"));
        PrintWriter pw = new PrintWriter(new FileWriter("users.txt"));
        String[] tab = null;
        String zlepek = "";
        while(br.readLine()!=null) {
            String line = br.readLine();
            tab = line.split("-");
            int countLoss = Integer.parseInt(tab[3]+plusLoss);
            int countWin = Integer.parseInt(tab[2]+plusWin);
            int countTie = Integer.parseInt(tab[4]+plusTie);
            if(tab[0].equals(loginUser.user)) {
                String newScore = (tab[0] + "-" + tab[1] + "-" + countWin + "-" + countLoss + "-" + countTie + "\n");
                zlepek = zlepek+newScore;
            } else {
                String oldScore = (tab[0] + "-" + tab[1] + "-" + tab[2] + "-" + tab[3] + "-" + tab[4] + "\n");
                zlepek = zlepek+oldScore;
            }   
        }
        pw.print(zlepek);
        pw.close();
        br.close();

        plusWin = 0;
        plusLoss = 0;
        plusTie = 0;

    } catch(IOException e) {} 

Any help is appreciated.


Solution

  • You are skipping the first line and every odd lines, change the code like below

        String line = null;
        while ((line = br.readLine()) != null){
                // code
        }
    

    also you are reading and writing on a same file, you can't read and write simultaneously on a same file. If you want you can write it to a temporary file and rename it later.

    If you want write on the same file, you have to close the reader before writing, see below

            BufferedReader br = new BufferedReader(new FileReader("users.txt"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            String zlepek = "";
    
            while ((line = br.readLine()) != null) {
                zlepek = // logic to get value
                sb.append(zlepek).append("\n");
            }
            br.close();
    
            PrintWriter pw = new PrintWriter(new FileWriter("users.txt")); // pass true to append
            pw.print(sb);
            pw.close();