我创建了一个这样的新文件:
File f = new File(filename);
if (!f.exists()) {
f.createNewFile();
}
我该怎么写?我只找到了如何使用Files.write
答案 0 :(得分:2)
您可以使用BufferedWriter这样的
File f = new File(filename);
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter(f));
bw.write("some data");
} catch (IOException ex)
{
//do something
} finally
{
if (bw != null)
{
try
{
bw.close();
} catch (IOException ex)
{
}
}
}
使用现代Java(7+),可以将其压缩为:
File f = new File(filename);
try(BufferedWriter bw = new BufferedWriter(new FileWriter(f)))
{
bw.write("some data");
} catch (IOException ex)
{
//do something
}