Java_FileInputStream及FileOutputStream详解_java文件拷贝的实现

本文深入讲解了Java中FileInputStream和FileOutputStream的使用方法,包括构造方法、读写操作及文件复制示例。通过实例演示了如何进行文件读取、字节流操作以及如何复制文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.6.3 FileInputStream与FileOutputStream的使用

2.6.3.1 FileInputStream类的的使用

1.FileInputStream的构造方法

  • new FileInputStream(String name) :从指定路径获得数据源,若文件不存在则抛异常
FileInputStream f = new FileInputStream("D:\\a.txt");
  • new FileInputStream(File file) 搭建一个File类的对象file对应的文件的数据流通道,文件不存在则抛异常
        File fileA = new File("D:\\b.txt");
		fileA.createNewFile();
		FileInputStream f = new FileInputStream(name); 
  • new FileInputStream(FileDescriptor fdObj) 搭建一个与FileDescriptor类对象描述的文件连接的数据流管道
        FileDescriptor a =new FileDescriptor();
		FileInputStream f = new FileInputStream(a);

2.FileInputStream的普通方法

  • read() :从这个输入流一次读取一个字节的数据

  • read(byte b[]):读取数据源的全部数据放到b byte数组中。

  • read(byte b[], int off, int len):从该输入流读取到字节数据。放入一个字节数组。off:数据中的起始偏移量(下标从0开始),len:写入的字数。

  • skip(long n):从当前位置跳过n个字节数。如一个文件中有ILOVEYOU内容

byte b[] =new byte[10];
long aa =4L;
f.skip(aa);
f.read(b)
//则b中只存有EYOU内容
  • available():返回可以读取的剩余字节数的估计值。

  • close():关闭流

  • getFD(): 获得FileDescriptor文件描述符

  • getChannel():返回文件通道

2.6.3.2 FileOutputStream类的使用方法

1.FileOutputStream的构造方法

构造方法用法与FileInputStream构造方法基本一致,详参FileInputStream构造方法

  • FileOutputStream(File file)
    创建文件输出流以写入由指定的 File对象表示的文件。如原文件中有数据,默认覆盖数据。
        File fileA = new File("D:\\b.txt");
		fileA.createNewFile();
		FileOutputStream f = new FileOutputStream(fileA); 
  • FileOutputStream(File file, boolean append)
    创建文件输出流以写入由指定的 File对象表示的文件。跟上一个布尔值,如true则表示如果原文件中有内容,则在此基础上追加写入数据而不覆盖。
FileOutputStream f = new FileOutputStream("D:\\a.txt",true)
  • FileOutputStream(FileDescriptor fdObj)
    创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。
  • FileOutputStream(String name)
    创建文件输出流以指定的名称写入文件。
  • FileOutputStream(String name, boolean append)
    创建文件输出流以指定的名称写入文件。跟上一个布尔值,如true则表示如果原文件中有内容,则在此基础上追加写入数据而不覆盖。

2.FileOutputStream的普通方法

  • write(int b) 将一个指定的整型数据写入输出流指向的文件
write(f.read()) //将输入流f当前读到的一个字节写入到输出流指向的文件中
write(99)  //将ASCLL码表中小写字母c对应的十进制整数99写入到输出流指向的文件中
  • write(byte b[]):从指定字节数组写入

  • write(byte b[], int off, int len)F:从指定字节数组写入。off:数据中的起始偏移量,len:写入的字数。

  • close():关闭流

  • getChannel():返回文件通道:

  • getFD():获得FileDescriptor文件描述符

2.6.4 使用字节流实现文件复制

将D:\b.txt中的内容复制到D:\新建文本.txt中去

public class TestFileInputStream {
	public static void main(String[] args) throws IOException {
		File name1 = new File("D:\\b.txt");
		name1.createNewFile();
		FileInputStream f = new FileInputStream(name1);
		FileOutputStream k = new FileOutputStream("D:\\新建文本.txt");
		byte[] b= new byte[(int) name1.length()];
		f.read(b);
		k.write(b);
		f.close();
		k.close();
	}

}

2.6.5 更多java知识请点击连接:

Scorpicat的博文

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值