Moshe Shaham Moshe Shaham -4 years ago 85
Java Question

How to write to a new File object

I created a new file like this:

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


how do I write to it? I only found how to write to a Path object using
Files.write

Answer Source

You can use a BufferedWriter like this

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)
        {
        }
    }
}

With modern Java (7+), this can be condensed as:

File f = new File(filename);
try(BufferedWriter bw = new BufferedWriter(new FileWriter(f)))
{
   bw.write("some data");
} catch (IOException ex)
{
    //do something 
} 

with the use of try-with-resources

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download