FileOutputStream
is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using
Java FileWriter.
FileOutputStream Constructors:
FileOutputStream Method:
Example Program:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
public static void main(String[] args) {
File file = new File("MeritCampus.txt");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// writes byte to the output stream
fop.write(65);
// flushes the content to the underlying stream
fop.flush();
fop.close();
System.out.println("File created.");
} catch (IOException e) {
e.printStackTrace();
}
int width = 300;
int height = 300;
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.setColor(Color.black);
g2.fillRect(0,0, width, height);
g2.setStroke(new BasicStroke(10.0f));
g2.setPaint(new GradientPaint(10,10, Color.green, 50,50, Color.blue, true));
g2.fill(new Ellipse2D.Float(50,50,200,200));
try (FileOutputStream out = new FileOutputStream("image.jpg")) {
ImageIO.write(bi, "jpg", out);
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("Image created.");
}
}
Output:
File created.
Image created.
//the following text file is created
/* This is the content of file : MeritCampus.txt
A
*/
//the following image is written on the system
Image:
Description:
A file
MeritCampus.txt
is created if it does not exist already. Byte is written on the
FileOutputStream
and the content is flushed to the underlying stream. An image is written on the second
FileOutputStream
and created. Note that the full path is to be given if the file or image is not to be created in the same folder as the
java
file on the system and this is a JDK7 example, where the new “try resource close” method to handle the file easily is used.
Things to try:
- Try to write the data from an array into the
FileOutputStream
using write(byte[] b)
method instead of using write(int b)
.
- Try to write the data from an array starting at the offset into the
FileOutputStream
using write(byte[] b, int off, int len)
method instead of using write(int b)
.
- Try writing different images in different formats by using
FileOutputStream
.