IO流之FileOutputStream(文件字节输出流)和FileInputStream(文件字节输入流)

IO流FileOutputStream(文件字节输出流)和FileInputStream(文件字节输入流)

import java.io.*;

public class FileByteinputAndoutput {

	public static void main(String[] args) {
		File f = new File("D:/word.txt");
		
		// 文件字节输出流
		FileOutputStream out = null; // 初始化对象
		try {
			// 如果目标路径文件不存在,会自动创建(前提是父路径文件对象必须存在),若文件存在,则会覆盖
			out = new FileOutputStream(f,false); // 属性 true 会在文件末尾追加内容,默认为 false
			
			String str = "你见过洛杉矶,凌晨四点的样子吗?"; // 定义一个字符串
			byte b[] = str.getBytes(); // 字符串转化为字节数组
			out.write(b); // 将字节数组写入到文件当中
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(out != null) { // 如果对象不为空
				try {
					out.close(); // 就关闭字节输出流
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		// 文件字节输入流
		FileInputStream in = null; // 初始化对象
		try {
			in = new FileInputStream(f); // 字节输入流读文件,如果目标路径文件不存在,不会自动创建
			
			byte b1[] = new byte[1024]; // 创建一个缓冲区
			int len; // 返回一个int值(读取缓冲区的总字节数)
			
			while((len = in.read(b1)) != -1) { // 读进缓冲区b1,一个字节一个字节的读取,读到最后会返回-1
				System.out.println("文件中的数据是:" + new String(b1,0,len)); // 从0读到len
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(in != null) { // 如果对象不为空
				try {
					in.close(); // 就关闭字节输入流
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅兮昂

你的支持是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值