-1

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

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.