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
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
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