15.4.1文件字节流 15.4.2文件字符流

FileInputStream  文件字节输入流     用来读文件
FileOutputStream  文件字节输出流  用来写文件

Demo类

public static void main(String[] args) {
		File f = new File("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 (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		FileInputStream in = null;//输入流
		
		try {
			in = new FileInputStream(f);//输入流读文件
			
			byte b2 [] = new byte[200];//缓冲区
			int len= in.read(b2);//读入缓冲区的总字节数
			System.out.println("文件中的数据是:"+new String(b2,0,len));//去掉多余空格
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			} catch (IOException e) {
			e.printStackTrace();
		}finally {
				if (out!=null) {
					try {
						in.close();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				}
			}
	}

 

15.4.2文件字符流

FileReader 文件字符输入流
FileWriter 文件字符输出流

public static void main(String[] args) {
		File f = new File("word.txt");
		
//		字符输出流
//		FileWriter fw = null;
//		try {
//			fw = new FileWriter(f,true);//true在源文件后追加新内容
//			
//			String str = "自强不息,天行健";
//			fw.write(str);//将字符串写入到文本文档
//			
//		}catch(IOException e) {
//			e.printStackTrace();
//		}finally {
//			if (fw!=null) {
//				
//				try {
//					fw.close();
//				}catch(IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}

//		字符输入流
		FileReader fr = null;
		try {
			fr = new FileReader(f);
			
			char ch[] = new char[1024];//缓冲区
			int count;//已经读出的字符数
			while ((count = fr.read(ch))!=-1) {//循环读取文件中的数据,直到所有字符都读完
				System.out.println("文件中的内容为:"+new String(ch,0,count));
				
				
				
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (fr!=null) {
				try {
					fr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值