How to write files

So I have this code:

import java.io.FileWriter;

FileWriter writeFile = new FileWriter("file.txt");

void setup()
{
  noLoop();
}

void draw() 
{
    writeFile.write("Hello World!");
    writeFile.close();
}

But the entire thing is giving me an error. It says that there is a Unhandelled exception type IOExcpetion? I am new to files in Processing, and I don’t know what I am doing wrong here. All I want to do is to create and write a file. Any help appreciated. Thanks.

1 Like

You can use a PrintWriter.

Example:

PrintWriter output;
output = createWriter("file.txt");
output.println("Hello World!");
output.flush();
output.close();

You do need to have both flush, and then close

1 Like

Oh, okay. I’m not familiar with PrintWirter though. How do you read the file?

 BufferedReader reader = createReader("file.txt");    

reader.readLine();
 //each time this is called it reads the next line of the file. Returns a String.
2 Likes

Oh and quick question, how do I append input to a file instead of completely overwriting it?

read the file, and then add new lines. Also if you want to get the length of the file it seems you have to use the other method to read it. I am using loadStrings. This returns a String[]. Using the method I have made below, you can just add lines to files.

void appendToFile(String str, String file) {
  String[] data = loadStrings(file);
  PrintWriter output = createWriter(file);

  for (int i=0; i < data.length; i++)
  {
    output.println(data[i]);
  }
  output.println(str);
  output.flush();
  output.close();
}


2 Likes