import java.io.*;

class FileReaderDemo
{
    public static void main(String[] args)
    {
        /*
            创建一个文件读取流,和指定名称的文件相关联。
            要保证该文件是已经存在的,如果不存在,会发生异常:FileNotFoundException
            创建对象引用:
        
*/
        FileReader fr = null;
        try
        {
            //实例化对象
            fr = new FileReader("demo.txt");
            
            /*
                读取单个字符:
                int c1 = fr.read();
                sop((char)c1);
                
                int c2 = fr.read();
                sop((char)c2);
                
                int c3 = fr.read();
                sop((char)c3);
                
                FileReader的read方法,在读取完一个字符后会自动向下读取,直到读到-1为止,这是一个循环动作
            
                while(true)
                {
                    int ch = fr.read();
                    if(-1!=ch)
                        break;
                        
                    sop((char)ch);
                }
            
*/
            
            //优化过的读取方式:
            int ch = 0;
            while((ch=fr.read()) != -1)
            {
                System.out.print((char)ch);
            }            
        }
        catch(IOException e)
        {
            sop("Error:"+e.getMessage());
        }
        finally
        {
            try            
            {
                if(null!=fr) fr.close();
            }
            catch(IOException e)
            {
                sop("Error:"+e.getMessage());
            }
        }
    }
    
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-08-26
  • 2021-11-20
  • 2021-12-28
  • 2022-12-23
  • 2021-06-01
猜你喜欢
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2021-09-09
  • 2021-08-18
相关资源
相似解决方案