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.
}
添加回答
举报