2 回答

TA貢獻1712條經驗 獲得超3個贊
只是為該答案添加更多詳細信息或替代方法,您可以使用try-with-resource塊,讓JVM為您關閉(并刷新)編寫器。
try(PrintWriter writer = ...))
{
writer.write("start");
}
catch (IOException e)
{
// Handle exception.
}
此外,您可以編寫一個實用程序函數來創建PrintWriter:
/**
* Opens the file for writing, creating the file if it doesn't exist. Bytes will
* be written to the end of the file rather than the beginning.
*
* The returned PrintWriter uses a BufferedWriter internally to write text to
* the file in an efficient manner.
*
* @param path
* the path to the file
* @param cs
* the charset to use for encoding
* @return a new PrintWriter
* @throws IOException
* if an I/O error occurs opening or creating the file
* @throws SecurityException
* in the case of the default provider, and a security manager is
* installed, the checkWrite method is invoked to check write access
* to the file
* @see Files#newBufferedWriter(Path, Charset, java.nio.file.OpenOption...)
*/
public static PrintWriter newAppendingPrintWriter(Path path, Charset cs) throws IOException
{
return new PrintWriter(Files.newBufferedWriter(path, cs, CREATE, APPEND, WRITE));
}
如果所有數據都可以在一個操作中寫入,則另一種可能性是使用Files.write():
try
{
byte[] bytes = "start".getBytes(StandardCharsets.UTF_8);
Files.write(file.toPath(), bytes)
}
catch (IOException e)
{
// Handle exception.
}
- 2 回答
- 0 關注
- 200 瀏覽
添加回答
舉報