如何写入新的File对象

时间:2017-03-23 09:21:39

标签: java

我创建了一个这样的新文件:

File f = new File(filename);
if (!f.exists()) {
    f.createNewFile();
}

我该怎么写?我只找到了如何使用Files.write

写入Path对象

1 个答案:

答案 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 
} 

使用try-with-resources