簡體   English   中英

我讀文件然后寫文件,文本之間的空格消失

[英]I read file then write the file and the spaces between text disappear

我從臨時文件中讀取並將其寫入永久文件,但某處字符串丟失了所有空格

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

沒有錯誤消息只是輸出應該是剩余空格的文件

這個:

while (scan.hasNext()) {
    sb.append(scan.next());
}

刪除空格是什么... next()將從掃描儀返回下一個完整的標記,這不包括空格。 您需要附加空格或更改您閱讀文件的方式......

從掃描儀文檔

掃描程序使用分隔符模式將其輸入分解為標記,分隔符模式默認匹配空格。

並從下一個方法文件

查找並返回此掃描程序中的下一個完整令牌。 在完成令牌之前和之后是與分隔符模式匹配的輸入。

換句話說,Scanner將輸入String拆分為沒有空格的序列。 要將文件作為String讀取,可以使用new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); 閱讀整個文件。

您可以逐行讀取文件,並在每行后面附加一個行分隔符,而不是掃描每個標記:

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

使用hasNextLine()nextLine()來逐行讀取filr,並在每行后面添加一個行分隔符,而不是hasNext()next()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM