Java FileOutputStream
Java FileOutputStream类是java.io包的一部分。
今天,我们将通过示例代码详细研究FileOutputStream类的构造函数和方法。
1. Java FileOutputStream
FileOutputStream是用于将数据写入File或者FileDescriptor的输出流。
FileOutputStream用于写入原始字节流,例如图像数据。
最好使用不能以文本表示的数据字节,例如PDF,excel文档,图像文件等。FileOutputStream类是OutputStream类的子类。
2. FileOutputStream类层次结构
3. FileOutputStream构造函数
FileOutputStream提供了将字节写入文件的方法,我们可以使用以下构造函数创建FileOutputStream的实例。
FileOutputStream(File file):创建一个文件输出流以写入指定文件对象表示的文件。
如果文件存在但是目录而不是常规文件,则不存在但无法创建,或者由于任何其他原因而无法打开文件,则抛出FileNotFoundException。FileOutputStream(File file,boolean append):创建一个文件输出流,以写入由指定File对象表示的文件。
如果第二个参数为true,则字节将被写入文件的末尾而不是开头。
如果文件存在但是目录而不是常规文件,则不存在但无法创建,或者由于任何其他原因而无法打开文件,则抛出FileNotFoundException。FileOutputStream(FileDescriptor fdObj):创建文件输出流以写入指定的文件描述符,该文件描述符表示与文件系统中实际文件的现有连接。
FileOutputStream(字符串名称):创建文件输出流以写入具有指定名称的文件。
FileOutputStream(字符串名称,布尔值追加):创建文件输出流以写入具有指定名称的文件。
如果第二个参数为true,则字节将被写入文件的末尾而不是开头。
如果文件存在但是目录而不是常规文件,则不存在但无法创建,或者由于任何其他原因而无法打开文件,则抛出FileNotFoundException。
4. Java FileOutputStream方法
让我们看一下FileOutputStream类的以下方法。
close():此方法关闭此文件输出流并释放与该流关联的所有系统资源。finalize():该方法清除与文件的连接,并确保在没有更多引用时调用此文件输出流的close()方法。getChannel():此方法返回与此文件输出流关联的唯一FileChannel对象。
返回的通道的初始位置将等于写入文件的字节数,将字节写入此流将增加通道的位置。getFD():此方法返回FileDescriptor对象,该对象表示与此FileOutputStream对象使用的文件系统中实际文件的连接。
write(byte [] b):此方法将b.length个字节从指定的字节数组写入此文件输出流。
write(byte [] b,int off,int len):此方法将指定字节数组中从offset off开始的len个字节写入此文件输出流。
write(int b):此方法将指定的字节写入此文件输出流。
实现OutputStream的write方法。
5.使用FileOutputStream Java写入文件
package com.theitroad.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream
*
* @author hyman
*
*/
public class FileOutputStreamWrite {
public static void main(String[] args) {
File file = null;
FileOutputStream fileOutputStream = null;
String data = "Hello World.";
try {
file = new File("D:/data/file.txt");
fileOutputStream = new FileOutputStream(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
Java 7提供带资源的try,这是一个声明一个或者多个资源的try语句。
资源是程序完成后必须关闭的对象。
try with resource语句可确保在语句末尾关闭每个资源。
让我们来看看如何重构以上程序,以对资源使用java try。
package com.theitroad.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream and try with resource
*
* @author hyman
*
*/
public class FileOutputStreamWriteTrywithResource {
public static void main(String[] args) {
File file = new File("D:/data/file.txt");
String data = "Hello World.";
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
还要检查java写入文件和java追加到文件以获取更多详细信息。
6. Java FileOutputStream示例
让我们通过一些示例程序来看看FileOutputStream的一些方法。
6.1)finalize()
FileOutputStream finalize()方法清除与文件的连接,并确保在没有更多引用时调用此文件输出流的close()方法。
如果在调用finalize()之后尝试访问FileOutputStream,我们将得到一个异常。
package com.theitroad.examples;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* Java FileOutputStream finalize method example
*
* @author hyman
*
*/
public class FileOutputStreamFinalizeExample extends FileOutputStream{
public FileOutputStreamFinalizeExample(File file) throws FileNotFoundException {
super(file);
}
public static void main(String[] args) {
File file = null;
try {
file = new File("D:/data/file.txt");
FileOutputStreamFinalizeExample fileOutputStream = new FileOutputStreamFinalizeExample(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//closing fileOutputStream
fileOutputStream.finalize();
//try to write data
fileOutputStream.write(123);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面程序的输出如下:
java.io.IOException: Stream Closed at java.io.FileOutputStream.write(Native Method) at java.io.FileOutputStream.write(Unknown Source) at com.theitroad.examples.FileOutputStreamFinalizeExample.main(FileOutputStreamFinalizeExample.java:31)
6.2)getFD()
FileOutputStream的getFD()方法返回FileDescriptor对象,该对象表示与此FileOutputStream对象使用的文件系统中实际文件的连接。
package com.theitroad.examples;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
/**
* Java FileOutputStream FileDescriptor Example
*
* @author hyman
*
*/
public class FileOutputStreamFileDescriptorExample {
public static void main(String[] args) {
File file = new File("D:/data/file.txt");
FileDescriptor fileDescriptor = null;
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
fileDescriptor = fileOutputStream.getFD();
boolean valid = fileDescriptor.valid();
System.out.println("Valid file: "+valid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
6.3)write(byte [] b,int off,int len)
此方法从指定的字节数组开始,以偏移量off开始向该文件输出流写入len个字节。
package com.theitroad.examples;
import java.io.File;
import java.io.FileOutputStream;
/**
* Java write file using FileOutputStream with write(byte[] b, int off, int len) method
*
* @author hyman
*
*/
public class FileOutputStreamWriteExample {
public static void main(String[] args) {
File file = null;
FileOutputStream fileOutputStream = null;
String data = "Hello World.";
try {
file = new File("D:/data/file.txt");
fileOutputStream = new FileOutputStream(file);
//create file if not exists
if (!file.exists()) {
file.createNewFile();
}
//fetch bytes from data
byte[] bs = data.getBytes();
fileOutputStream.write(bs, 0, 5);//only Hello will be written to a file
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}

