【问题标题】:I read file then write the file and the spaces between text disappear我读取文件然后写入文件,文本之间的空格消失
【发布时间】:2019-05-14 18:44:05
【问题描述】:

我正在从一个临时文件中读取并将其写入一个永久文件,但字符串在某处丢失了所有空格

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

没有错误消息,只是输出应该是一个带有空格的文件

【问题讨论】:

  • 你能举一个最小的例子吗?此代码处于无法运行的状态
  • 这是我的代码中的一个片段,但就像临时文件会说“whats up”例如然后我将它写入一个文件并且它仍然是“whats up”然后当我打开并将它写入此代码中的一个新文件改为“whatsup”。这是你问的吗?
  • 我的意思是我不能在家里复制/粘贴这段代码并破解它来查找问题。把你的整个代码库放在这里是无稽之谈。因此,请花一些时间将问题归结为一个重现您的问题的小示例。我可能只需阅读代码就可以做到;在这个过程中你我会发现问题
  • scan.hasNext() 中你只扫描字符串,而sb.append(scan.next()) 所以你只添加你正在扫描的字符串而没有空格。我建议你使用另一个类,如FileInputStream。或者像while(File != null)- 这样循环
  • 没有理由使用Scanner,是吗? StringBuilderPrintWriter 相同(使用 StringBuilder 写入已经具有 building {streaming} 功能的 *Writer 有点自相矛盾)

标签: java file-io java.util.scanner stringbuilder


【解决方案1】:

使用hasNextLine()nextLine() 代替hasNext()next() 来逐行读取文件并在每行后附加一个行分隔符:

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

【讨论】:

  • 谢谢,修复了
【解决方案2】:

来自扫描仪documentation

扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。

来自next methods docu

从这个扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是匹配分隔符模式的输入。

换句话说,扫描器将输入字符串拆分为没有空格的序列。要将文件作为字符串读取,您可以使用new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); 来读取整个文件。

【讨论】:

  • 啊,好的,谢谢,对不起,如果我的代码看起来很愚蠢,这是我第一次尝试这些东西
【解决方案3】:

这个:

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

是什么正在删除空格...next() 将从扫描仪返回下一个完整的令牌,这不包括空格。您将需要附加空格或更改读取文件的方式...

【讨论】:

    【解决方案4】:

    您可以逐行读取文件并在每行后附加一个行分隔符,而不是扫描每个标记:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 2017-10-22
      • 2012-12-29
      • 1970-01-01
      相关资源
      最近更新 更多