初学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是针对字节流的。