zoukankan      html  css  js  c++  java
  • java分享第七天-02(读取文件)

    一 读取文件

    public static void main(String[] args) throws FileNotFoundException,
                IOException {
            // 建立File对象
            File srcFile = new File("");
            // 选择流
            InputStream isInputStream = null;// 提升作用域
            try {
                isInputStream = new FileInputStream(srcFile);
                // 操作不断读取缓冲数组
                byte[] car = new byte[10];
                int len = 0;// 接收实际读取大小
                // 循环读取
                while (-1 != isInputStream.read(car)) {
                    // 输出字节数组转成字符串
                    String info = new String(car, 0, len);
                    System.err.println(info);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件不存在");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("读取文件失败");
            } finally {
                try {
                    if (null != isInputStream) {
                        isInputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("关闭文件输入流失败");
                }
            }
    
        }

    二写出文件

    public static void main(String[] args) throws FileNotFoundException,
                IOException {
            // 建立File对象目的地
            File dest = new File("");
            // 选择流,文件输出流OutputStream   FileOutputStream
            OutputStream out = null;// 提升作用域
            try {
                //true以追加的形式写出文件,否则是覆盖
                out = new FileOutputStream(dest,true);
                String str="abcdedg"; 
                //字符串转字节数组
                byte[] data=str.getBytes();
                out.write(data,0,data.length);
                    
                out.flush();//强制刷新出去
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件未找到");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("写出文件失败");
            } finally {
                try {
                    //释放资源:关闭
                    if (null != out) {
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("关闭文件输出流失败");
                }
            }
    
        }
  • 相关阅读:
    能够分页显示的Label控件
    C# winform 捕获全局异常
    纯C#钩子实现及应用
    C#对App.config文件或者web.config文件中节点的操作类
    C#中强制关闭某个进程
    VS2005中服务的启动,安装与卸载
    获取数据库表结构和表数据的小程序(VB.NET版本)
    使用ImessageFilter接口实现截获键盘或者鼠标的消息
    Windows_API_函数 参考大全
    系统升级程序的介绍
  • 原文地址:https://www.cnblogs.com/tiancy/p/6018935.html
Copyright © 2011-2022 走看看