-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

Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114
  • By creating a [`FileOutputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html) or a [`FileWriter`](https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html). – Elliott Frisch Mar 23 '17 at 09:23

1 Answers1

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

Edd
  • 1,350
  • 11
  • 14