[英]Why isn't BufferedWriter writing into file?
package com.mycompany.mavenproject1;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigDecimal;
public class Main {
public BufferedWriter writer;
public Main() {
Charset charset = Charset.forName("US-ASCII");
try {
this.writer = Files.newBufferedWriter(Paths.get("test.txt"), charset);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
public void print_fees(String msg, BigDecimal b) {
try {
int msg_len = msg.length();
int t;
t = 34 - msg_len;
t = t - 6;
this.writer.write(msg + String.format("%" + t + "s", b));
this.writer.newLine();
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
public static void main(String args[]) {
BigDecimal b = new BigDecimal(2);
Main obj = new Main();
try {
obj.print_fees("Fee: ", b);
} catch (Exception e) {
System.err.format("Exception: %s%n", e);
}
}
}
為什么 BufferedWriter 不寫入文件?
BufferedWriter 的重點是在將寫入的內容寫入任何底層實現之前將其緩沖到內存中。 當緩沖區填滿內存時,它會批量寫入。 這通常會提高寫入性能,因為對每個小寫入進行直接文件/磁盤寫入會由於 I/O 阻塞而降低性能。
您需要通過在寫入寫入器后調用BufferedWriter#flush()
來顯式刷新流以指示您希望將內存中的整個緩沖區寫入底層實現(在本例中為文件寫入器)。 例如, this.writer.flush()
。
此外,當您使用BufferedWriter#close()
完成打開的OutputStream
s/ Writer
時,您應該養成關閉它們的習慣。 BufferedWriter 將自動為您調用BufferedWriter#flush()
,將您的所有寫入寫入任何底層實現,而無需顯式調用BufferedWriter#flush()
。 例如,一旦你寫完你的Writer
就關閉你的 writer: this.writer.close()
this.writer.write(msg + String.format("%" + t + "s", b));
this.writer.flush();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.