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("关闭文件输出流失败");
                }
            }
    
        }
  • 相关阅读:
    $POST数组论证($GET || $COOKIE || $REQUEST 同理)
    PHP之preg_replace()与ereg_replace()正则匹配比较讲解
    PHP之mysql_real_escape_string()函数讲解
    浅析白盒审计中的字符编码及SQL注入
    PHP之list()函数讲解
    PHP之implode与explode函数讲解
    PHP之Error与Logging函数讲解
    Nextcloud私有云盘在Centos7下的部署笔记
    Linux下路由配置梳理
    实验c语言不同类型的指针互用(不推荐只是学习用)
  • 原文地址:https://www.cnblogs.com/tiancy/p/6018935.html
Copyright © 2011-2022 走看看