我正在从临时文件中读取并将其写入永久文件,但字符串在某个地方丢失了所有空格
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);
}
没有错误消息,只是输出应该是一个带有剩余空格的文件
最佳答案
不要使用 hasNext()
和 next()
来获取空格,而是使用 hasNextLine()
和 >nextLine()
逐行读取 filr 并在每行后面附加行分隔符:
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
sb.append(System.lineSeparator());
}
关于java - 我读取文件然后写入文件,文本之间的空格消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136684/