1,FileOutputStream概念
-
FileOutputStream 用于写入诸如图像数据之类的原始字节的流。用于将数据写入 File 或 FileDescriptor 的输出流。
2,构造方法
-
FileOutputStream(File file) file文件要是一个文件不是一个文件夹
file - 为了进行写入而打开的文件。
创建一个向指定 File 对象表示的文件中写入数据的文件输出流。创建一个新 FileDescriptor 对象来表示此文件连接。
首先,如果有安全管理器,则用 file 参数表示的路径作为参数来调用 checkWrite 方法。
如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开,则抛出 FileNotFoundException。
-
FileOutputStream(String name,boolean append)
name - 与系统有关的文件名
append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
-
FileOutputStream(File file, boolean append)
file - 为了进行写入而打开的文件。
append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
3,常用方法
4,实现写入文件
-
FileOutputStream fos = new FileOutputStream("yyy.txt",true); 第二个传true 则将字节写入文件末尾处,进行追加写入。 public class Demo2_FileOutputStream { /** * @param args * @throws IOException * FileOutputStream在创建对象的时候是如果没有这个文件会帮我创建出来 * 如果有这个文件就会先将文件清空 */ public static void main(String[] args) throws IOException { //demo1(); FileOutputStream fos = new FileOutputStream("yyy.txt",true); //如果想续写就在第二个参数传true fos.write(97); fos.write(98); fos.close(); } public static void demo1() throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream("yyy.txt"); //创建字节输出流对象,如果没有就自动创建一个 //fos.write(97); //虽然写出的是一个int数,但是到文件上的是一个字节,会自动去除前三个8位 //fos.write(98); //fos.write(99); fos.write(100); fos.close(); } }
5,自定义小数组进行读写操作
-
byte[] arr = new byte[2]; 去读,然后去写
-
fos.write(arr,0,len);
public class Demo4_ArrayCopy {
/**
* @param args
* 第三种拷贝
* 定义小数组
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("xxx.txt");
FileOutputStream fos = new FileOutputStream("yyy.txt");
byte[] arr = new byte[2];
int len;
while((len = fis.read(arr)) != -1) {
fos.write(arr,0,len);
}
fis.close();
fos.close();
}
}