FileOutputStream class
java.lang.Object
|
+-java.io.OutputStream
|
+-java.io.FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file.
Its most commonly used constructors are shown here:
FileOutputStream(String filePath)
- filePath is the full path name of a file
FileOutputStream(File fileObj)
- fileObj is a File object that describes the file.
FileOutputStream(String filePath, boolean append)
- filePath is the full path name of a file
FileOutputStream(File fileObj, boolean append)
- fileObj is a File object that describes the file.
If append is true, the file is opened in append mode.
Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will create the file before opening it for output when you create the object.
Opening a read-only file will throw an IOException.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) throws IOException {
byte buf[] = "this is a test".getBytes();
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i = 0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close();
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
OutputStream f2 = new FileOutputStream("file3.txt");
f2.write(buf, buf.length - buf.length / 4, buf.length / 4);
f2.close();
}
}
Methods from FileOutputStream
void close()
- Closes this file output stream and releases any system resources associated with this stream.
FileChannel getChannel()
- Returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD()
- Returns the file descriptor associated with this stream.
void write(byte[] b)
- Writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len)
- Writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b)
- Writes the specified byte to this file output stream.
Revised from Open JDK source code
Create FileOutputStream object from File object
import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/demo.txt");
FileOutputStream fos = new FileOutputStream(file);
}
}
Write file using FileOutputStream
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/demo.txt");
byte b = 01;
fos.write(b);
fos.close();
}
}