JAVA 字节流

一、FileOutputStream

该流用于写文件。

构造方法FileOutputStream(File file) 
              FileOutputStream(String name)

如:FileOutputStream fos = new FileOutputStream("fos.txt");

注:如果第二个参数为 true,即FileOutputStream fos = new FileOutputStream("fos.txt","true)  则将字节写入文件末尾处,而不是写入文件开始处。

创建字节输出流对象了做了几件事情:
  1、调用系统功能去创建文件,不用考虑有没有该文件。
  2、创建fos对象
  3、把fos对象指向这个文件

换行符:不同的系统针对不同的换行符号识别是不一样的 :windows:\r\n     linux:\n     Mac:\r

写入数据:public void write(int b):写一个字节
                  public void write(byte[] b):写一个字节数组
                  public void write(byte[] b,int off,int len):写一个字节数组的一部分

简单例子:

FileOutputStream fos = new FileOutputStream("fos3.txt", true);

		// 写数据
		for (int x = 0; x < 10; x++) {
			fos.write(("hello" + x).getBytes());
			fos.write("\r\n".getBytes());
		}

		// 释放资源
		fos.close();
	}

二、FileInputStream

该流用于读文件。构造方法与FileOutputStream一样。

int read():一次读取一个字节
int read(byte[] b):一次读取一个字节数组

实例:

        byte[] bys = new byte[1024];
		int len = 0;
		while ((len = fis.read(bys)) != -1) {
			System.out.print(new String(bys, 0, len));
		}

		// 释放资源
		fis.close();

三、文件的复制

public class CopyFileDemo {
	public static void main(String[] args) throws IOException {
		// 封装数据源
		FileInputStream fis = new FileInputStream("a.txt");
		// 封装目的地
		FileOutputStream fos = new FileOutputStream("b.txt");

		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = fis.read(bys)) != -1) {
			fos.write(bys, 0, len);
		}

		// 释放资源(先关谁都行)
		fos.close();
		fis.close();
	}
}

四、BufferedInputStream与BufferedOutputStream

它们的用法与FileInputStream和FileOutputStream基本一样。区别在于效率问题。这种方法的效率相对FileInputStream和FileOutputStream来说高一些。而且在生成对象时也有区别:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream( "bis.txt"));

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream( "bos.txt"));

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值