Java 字节流读写文件

Java:字节流读写文件

针对文件的读写,JDK专门提供了两个类,分别是 FileInputStreamFileOutputStream ,它们都是InputStream 的子类。

  • Example01:以字节流形式读取文件中的数据
  • Example02:将数据以字节流形式写入文件(覆盖文件内容)
  • Example03:将数据以字节流形式写入文件(追加文件内容)

1.FileInputStream 是操作文件的字节输入流,专门用于读取文件中的数据。

public class Example01 {
   public static void main(String[] args) throws IOException  {
   	FileInputStream in = new FileInputStream("Example1.txt");
   	int b = 0;
   	while(true) {
   		b = in.read();
   		if(b == -1) {
   			break;
   		}
   		System.out.println(b);
   	}
   	in.close();	
   }
}

注意:首先要确保文件 Example1.txt 存在并且可读,否则会抛出文件找不到的异常 FileNotFoundException

2.FileOutputStream 是操作文件的字节输出流,专门用于把数据写入文件。

public class Example02 {
	public static void main(String[] args) throws IOException {
		//创建一个文件字节输出流
		FileOutputStream out = new FileOutputStream("Example2.txt");
		String str = "****写入数据****";
		byte[] b = str.getBytes();
		for(int i=0; i<b.length; i++) {
			out.write(b[i]);
		}
		out.close();
	}
}

注意:程序运行后,会自动生成一个新的文本文件 Example2.txt 。如果 Example2.txt 已经存在数据,那么该文件中的数据会先被清空,再写入新的数据。

3.FileOutputStream 的构造函数 FileOutputStream(String fileName,boolean append) ,用于把数据追加写入文件。

public class Example03 {
	public static void main(String[] args) throws IOException {		
		FileOutputStream out = new FileOutputStream("Example2.txt", true);		
		String str = "----追加数据----";		
		byte[] b = str.getBytes();
		for(int i=0; i<b.length; i++) {
			out.write(b[i]);
		}
		out.close();
	}
}

注意:程序通过字节输出流对象向文件 Example2.txt 追加了数据。

由于IO流在进行数据读写操作时会出现异常,如果一旦遇到异常,IO流的 close() 方法将无法得到执行,流对象所占有的系统资源将得不到释放,因此,为了保证IO流的 close() 方法必须执行,通常将关闭流的操作写在 finally 代码块中。

finally{
	try{
		if(in != null)
			in.close();
	}catch(Exception e){
		e.printStackTrace();
	}
	try{
		if(out != null)
			out.close();
	}catch(Exception e){
		e.printStackTrace();
	}
}

希望能够帮助到大家! Java:字节数组和字符串的相互转化

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值