Java--io流及异常机制

2016-12-26  本文已影响0人  _Raye

IO流

public static void main(String[] args) {
        InputStream in = null;
        try {
            in = new FileInputStream("c:/MyJava/常用正则表达式.txt");
            int data;
            while ((data = in.read()) != -1) {
                System.out.printf("%x ",data);
            }
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();    
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            if (in != null) {
                try {
                    in.close();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
byte[] buffer = new byte[1024];
            int totalBytes;  //记录read操作总共读到了多少字节
            while ((totalBytes = in.read(buffer)) != -1){
                System.out.print(new String(buffer,0,totalBytes));
          } 
try(Writer writer = new FileWriter("c:/Users/apple/Desktop/abc.txt",true)){//true - 追加模式
            writer.write(s1 + "\r\n");//回车换行
            writer.write(s2 + "\r\n");
        }
        catch (IOException e) {
            e.printStackTrace();
        }

java异常机制

public static void main(String[] args) {
        InputStream in = null;
        try {
            in = new FileInputStream("c:/MyJava/常用正则表达式.txt");
            int data;
            while ((data = in.read()) != -1) {
                System.out.printf("%x ",data);
            }
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();    
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            if (in != null) {
                try {
                    in.close();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
try(InputStream in = new FileInputStream("c:/MyJava/常用正则表达式.txt")) {            
            byte[] buffer = new byte[1024];
            int totalBytes; 
            while ((totalBytes = in.read(buffer)) != -1){
                System.out.print(new String(buffer,0,totalBytes));
          }         
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();    
        } 
上一篇 下一篇

猜你喜欢

热点阅读