java I/O 系统

文件字节流(以字节为单位读取)

FileInputStream 文件字节输入流
FileOutputStream 文件字节输出流

package test;
import java.io.*;
public class test1{
	public static void main(String[] args) {
		File f=new File("word.txt");
		FileOutputStream out=null;
		try {
			out=new FileOutputStream(f,true);//创建为输出流
			//如果为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 b2[]=new byte[1024];//字符串转换为字节数组
			int num=in.read(b2);//
			System.out.println("文件中的数据是:"+new String(b2,0,num));
			
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		finally {
			if(in!=null) {
				try {
					in.close();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

文件字符流(以字符为单位进行读写)

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

package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class test1{
	public static void main(String[] args) {
		
		File f=new File("word.txt");
		
		FileWriter fw=null;			//字符输入流
		try {
			fw=new FileWriter(f,true);//true是在文件后添加内容,不写或false则为替换文件中的内容
			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) {//此时count是读取到的长度
				System.out.println("文件中的内容为:"+new String(ch,0,count));
			}
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			if(fr!=null) {
				try {
					fr.close();
				}catch(IOException e) {
				e.printStackTrace();
			}
		}	
	}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值