Search code examples
javafile-iojava.util.scannerstringbuilder

I read file then write the file and the spaces between text disappear


Im reading from a temp file and writing it to a permanent file but somewhere the string loses all its spaces

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String b, filename;
        b = null;
        filename = (textfieldb.getText());
        try {
            // TODO add your handling code here:
            dispose();
            Scanner scan;
            scan = new Scanner(new File("TempSave.txt"));
            StringBuilder sb = new StringBuilder();
            while (scan.hasNext()) {
                sb.append(scan.next());
            }
            b = sb.toString();
                    String c; 
        c = b;
        FileWriter fw = null;
        try {
            fw = new FileWriter(filename + ".txt");
        } catch (IOException ex) {
            Logger.getLogger(hiudsjh.class.getName()).log(Level.SEVERE, null, ex);
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.print(c);
        pw.close();
        System.out.println(c);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
          dispose();
        hiudsjh x = new hiudsjh();
        x.setVisible(true);

        System.out.println(b);
    } 

theres no error messages just the output should be a file with the spaces remaining


Solution

  • Instead of hasNext() and next() with which you don't get the spaces, use hasNextLine() and nextLine() to read the filr line by line and append after each line a line separator:

    while (scan.hasNextLine()) {
        sb.append(scan.nextLine());
        sb.append(System.lineSeparator());
    }