OutputStream此抽象类,是表示输出字节流的所有类的超类。操作的数据都是字节,定义了输出字节流的基本共性功能方法。
一、FileOutputStream类
OutputStream有很多子类,其中子类FileOutputStream可用来写入数据到文件。
FileOutputStream类,即文件输出流,是用于将数据写入 File
的输出流。
构造方法
二、FileOutputStream类写入数据到文件中
public class FileOutputStreamaa {
public static void main(String[] args) throws IOException {
//创建存储数据的文件。
File file = new File("c:\\file.txt");
//创建一个用于操作文件的字节输出流对象。一创建就必须明确数据存储目的地。
//输出流目的是文件,会自动创建。如果文件存在,则覆盖。
FileOutputStream fos = new FileOutputStream(file);
//调用父类中的write方法。
byte[] data = "abcde".getBytes();
fos.write(data);
//关闭流资源。
fos.close();
}
}
三、文件的续写和换行符号
FileOutputStream的构造函数中,可以接收一个boolean类型的值,如果值true,就会在文件末位继续添加,即续写。
构造方法
给文件中续写数据和换行
public class FileOutputStreamDemo2 {
public static void main(String[] args) throws Exception {
File file = new File("c:\\file.txt");
FileOutputStream fos = new FileOutputStream(file, true); //true设置给指定文件续写数据
String str = "\r\n"+"itcast"; // "\r\n"实现换行
fos.write(str.getBytes());
fos.close();
}
}
四、IO异常的处理
我们在实际开发中,异常时如何处理
public class FileOutputStreamDemo3 {
public static void main(String[] args) {
File file = new File("c:\\file.txt");
//定义FileOutputStream的引用
FileOutputStream fos = null;
try {
//创建FileOutputStream对象
fos = new FileOutputStream(file);
//写出数据
fos.write("abcde".getBytes());
} catch (IOException e) {
System.out.println(e.toString() + "----");
throw new RuntimeException("文件写入失败,请重试");
} finally {
//一定要判断fos是否为null,只有不为null时,才可以关闭资源
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException("关闭资源失败");
}
}
}
}
}