IO

 

一、Java的标准数据流

 

1.System.in

          作为字节输入流类InputStream的对象in实现标准的输入,其中有read方法从键盘接收数据。

2. System.out

           作为打印流类PrintStream的对象out实现标准输出。其中有print和println两个方法,这两个方法支持java的任意的基本类型作为参数。

3. System.err

         与System.out相同,以PrintStream类的对象err实现标准的错误输出。

二、读取数据的方法

int read() throws IOException ;

int read(byte[] b) throws IOException ;

int read(byte[] b,int off,int len) throws IOException ;

 

注意:read方法若返回-1,则表明当前读取位置已经到达流的末尾。

例如:int n;

While((n=fis.read())!=-1)

{

       //数据处理

}

三、 文件字节输入/输出流类

FileInputStream用于顺序访问本地文件。它从父类InputStream中继承read()、close()等方法对本机上的文件进行操作,但不支持mark()方法和reset()方法。

¯    例:例题:打开文件

import java.io.*;

public class ReadFileTest

{

   public static void main(String[] args) throws IOException

   {

        try

        {

            //创建文件输入流对象

FileInputStream fis =new FileInputStream("ReadFileTest.java");     

         int n=fis.available();       

         byte b[]=new byte[n];       

         //读取输入流        

         while((fis.read(b,0,n))!=-1)   

         {                 

         System.out.print(new String(b));          

         }

         System.out.println();

         //关闭输入流

         fis.close();   

      }

      catch(IOException ioe)

      {

         System.out.println(ioe.getMessage());

      }

      catch(Exception e)

      {

         System.out.println(e.getMessage());

      }

      }

}

 

 

 

 

 

 

你可能感兴趣的:(IO)