FileInputStream和read函数的使用

    初学java,菜鸟笔记。

    如何使用FileInputStream类读取文件中的数据。

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

public class testtt3 {
	public static void main(String[] args) {
		FileInputStream fin=null; //对象在try外声明,否则离开了try作用域就从栈中抹掉了。
		try{
			fin=new FileInputStream("/home/wangzheng/java_test/myfile.txt");
		}catch(FileNotFoundException e){
			System.out.println("未找到对应文件。");
			e.printStackTrace();
		}
		int count=0;
		try{
			int b;
                        //在使用read()时读取的内容将以int类型返回,需要强制转换为char类型。
                        //显然,如果文本中只有数字和英语字母,程序可以正常工作,因为虽然java使用的是16位的unicode字符编码,
                        //但是数字和英文字母的编码值在255以内,因此使用字节流读入可行,但如果加入汉字,该程序将显示乱码。
                        while((b=fin.read())!=-1){
		                count++;//统计字符的个数。
                                System.out.print((char)b);//打印读到的字符。
	                }
	        }catch(IOException e){
		        e.printStackTrace();
	        }
		System.out.println();
		System.out.println(count);//输出个数。
	}
}
    时刻牢记,FileInputStream是针对字节流的。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值