IO学习(四)文件读取与写出

要读取一个文件,有以下几个步骤:

1.建立与文件的联系:File对象,文件必须存在

2.选择流:按字节流读取,文件输入流 InputStream FileInputStream

3.操作:byte[] car=new byte[1024]+read

4.释放资源,注意jdk1.7后会自动关闭了



InputStream是一个抽象类,不能new一个新的对象,所以这里使用多态

InputStream is=new FileInputStream(......);

选择构造方法,第一个和第三个比较常用,本质上来说这两种方法是一致的,通过String name 创建一个新对象,

它内部还是会通过name包装成File



在读取文件时,使用循环不断进行读取,定义一个制定长度的byte数组,则这个数组就是每次读取文件的长度,

如果要输出,就创建一个String对象,String info = new String(car, 开始, 结束); 


public class Demo02 {
	public static void main(String[] args) {
		File src = new File("F:/Picture/test.txt");
		InputStream is = null;
		try {
			is = new FileInputStream(src);
			
			// 缓冲数组
			byte[] car = new byte[8];
			
			// 实际读取大小
			int len = 0;
			
			// 循环读取
			while (-1 != (len = is.read(car))) {
				// 输出 字节数组转为字符串
				String info = new String(car, 0, len);
				System.out.println(info);
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}






文件写出,有以下几个步骤:

1.建立与文件的联系:File对象,文件可不存在

2.选择流:按字节流写出,文件输出流 OutputStream FileOutputStream

3.操作:write+flush

4.释放资源,注意jdk1.7后会自动关闭了



FileOutputStream的构造方法

FileOutputStream(File file,boolean append) 如果选择true,则是追加,false则覆盖

构造方法中没有append参数的,则默认false,覆盖



public class Demo02 {
	public static void main(String[] args) {
		
		File dest=new File("F:/Picture/test.txt");
		OutputStream os=null;
		try {
			os=new FileOutputStream(dest);
			String str="hahahaha";
			
			//字符串转字节数组
			byte[] data=str.getBytes();
			
			os.write(data,0,data.length);
			
			//强制刷新出去
			os.flush();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			try {
				if(null!=os){
					os.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值