[英]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()
將從掃描儀返回下一個完整的標記,這不包括空格。 您需要附加空格或更改您閱讀文件的方式......
您可以逐行讀取文件,並在每行后面附加一個行分隔符,而不是掃描每個標記:
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.