JavaI/O文件读写:字节输出流

2022年12月14日  补充:

字节流输出流(写数据到硬盘)

实用子类: FileOutputStream类

构造:

  • public FileOutputStream(File file):创建文件输出流以写入由指定的 File对象表示的文件。
  • public FileOutputStream(String name): 创建文件输出流以指定的路径写入文件。

必须传入一个文件或者路径。如果没有这个文件,会创建该文件。如果有这个文件,创建一个新的空白文件覆盖已有的文件。(路径必须有)

代码:

        FileOutputStream f  = new FileOutputStream("1.txt");
        f.write(99);  //c
        f.write(100);  // d
        f.close();

 一次写多个数据

      //可以直接写入一个byte数组
        fos.write(new byte[]{66, 67, 68, 69, 70});

        //把字符串转为byte数组 输出到文件
        fos.write("你好fdsfs".getBytes());

        //write(byte b[], int off, int len)
        //off偏移量 表示跳过几个数据
        //len数量 表示写入几个数据
        byte[] bs = {71, 72, 73, 74, 75};
        //把bs数组 偏移一个 然后写到文件里3个字节 这里是72 73 74写到文件里了
        fos.write(bs, 1, 3);

如果要写入字符串,就把字符串通过getBytes()方法转为byte数组   

fos.write("你好吗哈哈哈".getBytes());

 追加与换行

  • - windows:\r\n
    - linux:\n
    - mac:\r

- public FileOutputStream(String name,boolean append)
- 创建文件输出流以指定的名称写入文件。如果第二个参数为true ,则字节将写入文件的末尾而不是开头

 

//第二个参数为true 表示从后面追加写入数据
FileOutputStream fos = new FileOutputStream("module01/aaa/c.txt",true);

for (int i = 0; i < 5; i++) {
    fos.write("你好吗哈哈哈".getBytes());
    //回车   换行
    fos.write("\r\n".getBytes());
}

//3关闭流  把文件资源释放
fos.close();

 


字节输出流:FileOutputStream

package IO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Zifushuchu {
    //字节输出流:FileOutputStream
	public static void main(String[] args) {
		String a="hahah";
		FileOutputStream fos=null;
		try {
			fos=new FileOutputStream("C:\\456.txt",true); //不加true为覆盖写入 加上表示追加写入
			byte[] words=a.getBytes();  //将要写入的字符串转换成字节数组
			fos.write(words,0,words.length);  //写入文件
			fos.flush(); //清空缓存区数据,并强制写入
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

以上程序将

hahah写入

C:\\456.txt

阅读剩余
THE END