File f =new File("~"); //创建源
InputStream is =new FileInputStream(f); //选择流
is.read() 读取单个数据,并使游标下移 //操作(读取)
is.close() //释放资源,输入流读取后必须释放资源
public class test{
public static void main(String[]args)
{
//创建源
File f=new File("C:/Users/10853/eclipse-workspace/hell/src/hell/abc");
InputStream is =null;//提升is的作用域,避免在try中声明后,作用域
//只在try,finally中语句无法执行
//选择流
try {
is =new FileInputStream(f);
//操作(读取)
int temp;
while((temp=is.read())!=-1) //temp=is.read()表达式整体的值就是temp的值
{ //is.read()会读取单个数据,当数据读取完毕时,返回-1
System.out.println((char)temp);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
if(null!=is)//当is创建成功时才执行关闭
{
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
原文地址:https://blog.51cto.com/14437184/2422845
时间: 2024-10-10 10:33:12