IO流

intro

输入输出流是数据处理的通道,java为之有相应的类和接口。

文件输入流

package stream;

import java.io.file;
import java.io.FileInputStream;
import java.io.IOException;

public class TestStream{
	public static void main(String args[]) {
		trt{
			File f = new File("d:/file.txt");
			FileInputStream fis = new FileInputStream(f);
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

要先通过File获得文件句柄,然后再作为参数传入FileInputStream流中。如果要输出,就喂入到FileOutputStream。

字节流

字符流也一样的。

以字节流的形式读取文件内容

用于以字节的形式读取和写入数据。

package stream;

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

public class TestStream{
	public static void main(String[] args) {
		try{
			File f = new File("d:/input.txt");
			FileInputStream fis = New FilInputStream(f);
			byte[] all =  new byte[(int) f.length];
			fis.read(all);
			for(byte b : all){
				Sytem.out.printlb(b);
			} 

			fis.close();
		}catch(IOException e) {
			e.printStack();
		}
	}
}

创建了一个Byte数组,用于存储file的字节数据。一个ASCii码对应一个字节。

关闭流的方式

无论是输入流还是输出流,如果使用完之后,不关闭数据流,会产生对资源的占用。

在try中关闭

package stream;

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

public class TestStream{
	public static void main(String args[]){
		try{
			File f = new File("d:/input.txt");
			FileInnputStream fis = new FileInputStream(f);
			byte[] all = new byte[(int) f.length];
			fis.read(all);
			for(byte b : all) {
				System.out.println(b);
			} 
			fis.close(); //close the stream.
		}catch(IOException e) {
			e.printStackTrace();
		}
	}

}

在finally中关闭

当然也可以在finally中关闭,注意要在close前检查有没有成功创建文件流,即fis是否为空。

package stream;

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

public class TestStream{
	public static void main(String args[]){
		try{
			File f = new File("d:/input.txt");
			FileInputStream fis = new FileInputStream(f);
			byte[] all = new byte[(int) .length()];
			fis.read(all); //从文件读到文件
			for(byte b : all) {
				System.out.println(b);
			]
		} catch(IOException e) {
			e.printStackTrace();
		} Finally{
			if(fis != null) {
				try{
					fis.close();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

汉字的编码方式


Reference

[1] https://how2j.cn/k/io/io-encoding/695.html#nowhere

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值