How to Write to a file with JAVA
The task of writing to a file with Java is greatly simplified with Input/Output streams. These are a group of classes used for basic I/O and include classes for serialization that allows a program to read and write entire objects to a stream. Many methods of writing to a file can be employed and they are included in the java.io package. Here's a simple example of writing to a file with Java.
Instructions
-
-
1
Import all of the needed classes. We import each class individually for the purposes of illustration but we could import the entire package with the statement "import java.io.*."
-
2
Declare a FileInputStream object for the input and output files and instantiate them with the desired input and output file names (input.txt and output.txt, respectively).
-
-
3
Use the write method of the FileOutputStream class to write to the output file. Other methods are available for writing to a file, but write is used here as the simplest possible example.
-
4
Notice how the program stays in a loop that reads a byte from the input stream and writes the byte to the output stream until the end of the input file is reached.
-
5
Look at the complete code for this example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class WriteBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
int i;
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");while ((i = in.read()) != -1){
out.write(i);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
-
1