Now, let’s take a closer look at
FileOutputStream is used to output data from a program into a file. Like
FileOutputStream writes in bytes and then converts to the variables a program or file requires accordingly.
We still import the class into a program outside of the class using the following statement:
Step 1: Declare your output stream.
FileOutputStream output = new FileOutputStream("output.txt") will create a file named output.txt in the same folder as where your Java program is saved. You may also choose to place an absolute or relative file path in the brackets.
Alternatively, you may choose to create an object of the variable type
File to pass into the
FileOutputStream. This is useful if you plan to have the user pass in a path where they want to store the output:
//Option 1: Pass file path/name directly to FileOutputStream FileOutputStream output1 = new FileOutputStream("output.txt"); // Option 2: Use File object to pass file info to FileOutputStream // Save file path that has been passed in by the user into a string variable. String fileName = args; // Pass path to File object File outputFile = new File(fileName); // Pass File object to FileOutputSteam FileOutputStream output2 = new FileOutputStream(outputFile);
Step 2: Write to your file.
This is achieved using the
write() function. Since
FileOutputStream uses bytes, we must convert the data we wish to write to a file into bytes and then write to the file. Let’s assume we are passing the string
statement to a file.
// Declare FileOutputSteam FileOutputStream output = new FileOutputStream("output.txt"); // Declare statement String statement = "Hello World!"; // Convert statement to bytes. byte statementBytes = statement.getBytes(); // Option 1: // Write all contents to file output.write(statementBytes); // You can do this more succinctly using output.write(statement.getBytes()); // Option 2: // If you want to write specific bytes to a file you may choose to use the following statement // output.write(byte bytes, int startingIndex, int endingIndex); output.write(statementBytes, 0, 4);
Step 3: Close the file.
It is important we close a file once we are done writing to it. To do this, we use the
Import the entire
io class at the top of your program, then declare an
IOException in your main method header.
FileOutputStream object using
"output.txt", which will be the name of our file.
Now it’s time to write to our file! In the following order:
- Create a
outputTextand set it to any message you want
- Convert that text to bytes using the
- Lastly, use
write()to write the translated bytes to your
Finally, close your