文件流

在字节流中,暂时不要使用中文.
FileInputStream:     文件的字节输入流
FileOutputStream:  文件的字节输出流
FileReader:文件的字符输入流

FileWriter:文件的字符输出流

文件字节输入流:

public class FileInputStreamDemo {
	public static void main(String[] args) throws Exception {
		//1.创建源
		File f = new File("file/stream.txt");
		//2.创建文件字节输入流对象
		InputStream in = new FileInputStream(f);
		//3.具体的读写操作
		/**
		 * int read():
		 * int read(byte[] b):
		 * int read(byte[] b,int off,int len):
		 */
		byte[] buffer = new byte[8];
		System.out.println(Arrays.toString(buffer));
		/*int ret = in.read(buffer);
		String str = new String (buffer,0,7);
		System.out.println(str);
		System.out.println(Arrays.toString(buffer));*/
		int ret = in.read(buffer,2,6);
		System.out.println(Arrays.toString(buffer));
		/*int len = -1;
		while((len = in.read(buffer))!=-1){
			String str = new String (buffer,0,len);
			System.out.println(str);
		}*/
		in.close();
	}
}

文件字节输出流:

public class FileOutputStreamDemo {
	public static void main(String[] args) throws Exception {
		//1.创建目标对象(数据保存到哪一个文件)
		File targe = new File("file/stream.txt");
		//2.创建文件字节输出流对象
		OutputStream out = new FileOutputStream(targe,true);
		//3.具体的输出操作
		/**
		 * void write(int b):把一个字节写出到文件中
		 * void write(byte[] b):把数组b中的所有的字节都写出到文件中
		 * void write(byte[] b, int off,int len):把数组中的从索引off开始的len个字节写出到文件中
		 * */
		out.write("abcdefghijklmn".getBytes(),5,4);
		//关闭资源
		out.close();
	}

}

使用文件字符流完成文件的拷贝(纯文本文件):

public class FileCopyDemo {
	public static void main(String[] args) throws Exception {
		//1.创建源或目标文件
		File srcFile = new File("file/aa.txt");
		File destFile = new File("file/aa_copy.txt");
		//2.穿建输入流和输出流对象
		Reader in = new FileReader(srcFile);
		Writer out = new FileWriter(destFile);
		//读和写操作
		char[] buffer = new char[100];
		int len = -1;
		while((len = in.read(buffer))!=-1){
			out.write(buffer,0,len);
		}
		//关闭流
		out.close();
		in.close();
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值