FileOutputStream、FileInputStream、FileReader和FileWriter类(简单代码例子实现)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main{  
	 public static void  main(String[] args) {
		 //文件字节流
		 File f = new File("word.txt");//创建文件word.txt
		 
		 //输出流FileOutputStream,将数据输出到word.txt
		 //不可以在word.txt中直接编辑,除非FileOutputStream被注释了(try-catch是系统自动填充的)
		 try {
			 FileOutputStream out = new FileOutputStream(f,false);;//创建FileOutputStream对象
			 //false文件输出流,在文件末尾不可追加,默认;true文件输出流,在文件末尾可追加
			String s  = "你好啊;";
			byte b[] = s.getBytes();//字符串装换为字节数组
			
			out.write(b);//将字节数组中的数据写入到文件当中
		
			out.close();//java在程序结束时自动关闭所有打开的流,但是当使用完留后,显示的关闭是所有打开的流是一个好习惯

		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		 
		 //输入流FileInputStream,将数据读出来
		 FileInputStream in = null ;
		 try {
			in = new FileInputStream(f);//输出流读文件
			
			byte b2[] = new byte[1024];//缓存区1024个字节,有空格的产生
			
			int len = in.read(b2);//读入缓存区的总字节数
//			System.out.println("文件中的内容是:" +new String(b2));//不去掉空格
			System.out.println("文件中的内容是:" +new String(b2,0,len));//去掉空格
	
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			if( in != null) {
				try {
					//java在程序结束时自动关闭所有打开的流,但是当使用完留后,显示的关闭是所有打开的流是一个好习惯
					in.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}

//第二部分:文件字符流
			/* //文件字符流(因为,文件字节流的读取的单位是字节(一个汉字两个字节),如果文件读取的字节数量没有控制好就会出现乱码,所以用了字符流来避免了这种问题)
		 File f = new File("word.txt");//创建文件word.txt
		 
		 
//		 try {
//			FileWriter fw = new FileWriter(f,true);
//			
//			String str = "我有一只小毛驴1";
//			fw.write(str);//将字符串写入文本文档
//			
//			fw.close();//关闭流
//		} catch (IOException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
		 
		 try {
			FileReader fr = new FileReader(f);
			
			char ch[] = new char[1024];//缓存区
			int count  = fr.read(ch); //从文件中读取数据,将数据传给ch,返回值是length
			while(count!= -1) {
				System.out.println("文件中的内容为 : " + new String(ch,0,count)); 
			}			
			fr.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}*/
		  
		 
	 }
}

运行结果:在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值