IO流作业

2023-11-17

io(文件操作)

in (读取) out(写出)

java.io.File

常用的三个构造方法:

/*
 *File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
 */
public class Demo01 {
    public  static  void  main(String[]args) throws IOException {
        File file  = new File("D://1.txt");
        boolean flag = file.createNewFile ();//当且仅当具有此名称的文件尚不存在时,以原子方式创建                                                  由此抽象路径名命名的新空文件。
        System.out.println (flag?"创建成功":"创建失败");
    }
}
/*
 *File(File parent, String child) //先传一个文件夹,在文件夹里创建文件。
 */
public class Demo02 {
    public  static  void  main(String[]args) throws IOException {
        File file  = new File("D://hahaha");
        //boolean flag = file.mkdir (); //创建文件夹

        //System.out.println (flag?"创建成功":"创建失败");

        File dir = new File(file,"a.txt");
          dir.createNewFile ();
    /*
     *File(String parent, String child)//先传字符串路径,在文件夹里创建文件。
     */
        File dd = new File ("D://hahaha","c.txt");
             dd.createNewFile ();
    }
}

常用方法:

    避免跨平台;路径分隔符出错,替换成字段

​ pathSeparator 与系统相关的路径分隔符,为方便起见,表示为字符串。 //详细见File -字段

文件遍历案例

public class Demo03 {
    public  static  void  main(String[]args) throws IOException {
        File e = new File ("E:\\");
        File [] files = e.listFiles ();
        ListFiles(files);
    }

    private static void ListFiles(File[] files) {
        if(files != null && files.length>0){
            for( File file:files) {
                if (file.isFile ()) { //判断是否为文件
                    if (file.getName ().endsWith (".pdf")) {
                        //找到一个avi文件
                        if(file.length ()>10*1024*1024) {
                            System.out.println ("找到一个avi文件:" + file.getAbsolutePath ());
                        }
                        }
                }else {
                    File[] file2 = file.listFiles ();
                    ListFiles (file2);
                }
            }
        }
    }
}

文件过滤器

了解即可

相对路径与绝对路径

​ 相对路径:Java中不完整路径 ,相对于项目下的路径,a.txt.

​ 绝对路径:路径只能拿到一个文件,c://a.txt.

流概述(文件内容)

*Io流概述
* 可以将这种数据操作,看作是一种数据的流动,按照流动的方向分为输入Input和输出Output
* Java中的IO操作主要指的是java.io包下的一些常用类的使用,通过这些常用类对数据
* 进行读取(输入Input)和写出(输出Output)
*
* IO流的分类
* c
*
*       字节流:
*              - 输入流:(顶级父类)InputStream
*              - 输出流: ()OutputStream
*       字符流:
*              -输入流:Reader
*              -输出流:Writer
 *   一切皆字节:
 *        计算机中任何数据(文本,图片,音乐等等) 都是以二进制的形式存储的。
 *        在数据传输时,在数据传输时,也都是以二进制的形式存储的。
 *         后续学习的任何流,在数据底层都是二进制

*/

java.io.OutputStream

    write(byte[] b, int off, int len) //从off开始 ,len= 写的个数

    write(int b) 将指定的字节写入此输出流。 //输入是int,传出wei字节

java.io.FileOutputStream

​ 构造方法:

​ FileOutputStream(FileDescriptor fdObj) 创建要写入指定文件描述符的文件输出流,该文件描述符表示与文件系统中实际文件的现有连接。

​ FileOutputStream(File file, boolean append) 创建文件输出流以写入由指定的 File对象表示的文件。

​ FileOutputStream(String name) 创建文件输出流以写入具有指定名称的文件。

​ FileOutputStream(String name, boolean append) 创建文件输出流以写入具有指定名称的文件。

1.3传入的是对象

​ 4,5传的是路径

public class Demo05 {
    public  static  void  main(String[]args) throws IOException {
       //FileOutputStream
        FileOutputStream fos = new FileOutputStream ("d://a.txt",true);
        byte [] bytes = {65,56,78,56,46};
        fos.write (bytes);
        fos.close ();
        System.out.println ("已经写出");
    }
}
java.io.FileInputStream

​ 构造方法

​ FileInputStream(File file) //通过打开与实际文件的连接来创建FileInputStream ,该文件由文件系统中的 File对象 file命名。(对象)

	 	FileInputStream(FileDescriptor fdObj)    //使用文件描述符 fdObj创建 FileInputStream ,该文件描述符																							表示与文件系统中实际文件的现有连接。

​ FileInputStream(String name) //通过打开与实际文件的连接来创建 FileInputStream ,该文件由 文件系统中的路径名 name命名。 (路径)

​ 方法

			close()       关闭此文件输入流并释放与该流关联的所有系统资源。

​ read() 从输入流中读取下一个数据字节。 从输入流中读取下一个数据字节。 值字节返回int ,范围 为0至255 。 如果由于到达流末尾而没有可用字节,则返回值-1 。 此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常。

​ read(byte[] b) 从输入流中读取一些字节数并将它们存储到缓冲区数组 b 。//最后一次读取,如果不够一组,元数据不会被完全清空。

读取一个字的方法 read() 

public class Demo06 {
    public  static  void  main(String[]args) throws IOException {
       //FileInputStream
        FileInputStream fis = new FileInputStream ("d://a.txt");
//        byte b = (byte) fis.read();
//        System.out.println ((char) b);
//        byte c = (byte) fis.read ();
//        System.out.println ((char) c);
        while (true){
            byte b = (byte) fis.read ();//读的内容超出最后一个,返回-1;不会报错,除非内存溢出
            if(b==-1){
                break;
            }
            System.out.println ((char) b);

        }
          fis.close ();
    }
}
 */读一组数
 用返回值是否为-1来判断我们打印几次
public class Demo07 {
    public  static  void  main(String[]args) throws IOException {
       //FileInputStream
        FileInputStream fis = new FileInputStream ("d://a.txt");
             byte [] bytes = new byte[10];
             int len = fis.read (bytes);
              System.out.println (new String (bytes,0,len));
             len = fis.read (bytes);
             System.out.println (new String (bytes,0,len));
             len = fis.read (bytes);
             System.out.println (new String (bytes,0,len));
 				
          fis.close ();
    }
}

用返回值是否为-1来判断我们打印几或者是判断len

public class Demo07 {
    public static void main(String[] args) throws IOException {
        //FileInputStream
        FileInputStream fis = new FileInputStream ("d://a.txt");
        byte[] bytes = new byte[10];
        int len;
        while (true) {
             len = fis.read (bytes);

            System.out.println (new String (bytes, 0, len));
            if(len<10){
                break;
            }
            or
            if(fis.read () ==-1){
                break;
            }
        }
        fis.close ();
    }
}

文件加密和解密工具

/*
 *文件加密或解密
 */
public class Demo08 {
    public  static  void  main(String[]args) throws IOException {

        System.out.println ("请输入文件存储的全路径:");
        Scanner input = new Scanner (System.in);
        String  name = input.nextLine ();
        //原文件: 777.pdf
        File oidFile = new File (name);
        //加密存储文件 mi-777.pdf
        File newFile = new File (oidFile.getParentFile (),"mi-"+oidFile.getName ());

        FileInputStream fis = new FileInputStream (oidFile);
        FileOutputStream fos = new FileOutputStream (newFile);
        while (true) {
            int b = fis.read ();
            if(b==-1{
                break;
            }
            //任何数据^相同的数字两次,结果就是其本身
            fos.write (b^10);
        }
        System.out.println("加密或解密已完成");
    }
}

字符输出

public class Demo09 {
    public  static  void  main(String[]args) throws IOException {
        //Writer

        FileWriter fw = new FileWriter ("d://f.txt",true);//true:是追加模式,没有的相对于清空
        fw.write ("锄禾日党务,汗滴禾下土");
        System.out.println ("擦胡歌");
        fw.close ();
    }
}

append ()

public class Demo09 {
    public  static  void  main(String[]args) throws IOException {
        //Writer

        FileWriter fw = new FileWriter ("d://f.txt",true);
//        fw.write ("锄禾日党务,汗滴禾下土")
        FileWriter fw2   = (FileWriter) fw.append ("鹅鹅鹅,去学习系统");//append()//追加,且返回this
          fw.append ("鹅鹅鹅,去学习系统").append("测试测试测试");
        @Override
        public Writer append(CharSequence csq) throws IOException {
            if (csq instanceof CharBuffer) {
                se.write((CharBuffer) csq);
            } else {
                se.write(String.valueOf(csq));
            }
            return this;
//        }
        System.out.println ("fw ==fw2");
        fw.close ();
    }
}

字符读取

/*
 *字符输入
 */
public class Demo10 {
    public  static  void  main(String[]args) throws IOException {
        //Reader
        FileReader fr = new FileReader ("d://f.txt");
//        while(true){
//            int c=fr.read ();
//            if(c==-1){
//                break;
//            }
//               System.out.print ((char) c);//一个个的读
//        }
        char [] chars = new char[100];
          int len = fr.read (chars);
          String text = new String (chars,0,len);
          System.out.println (text);
        fr.close ();//关闭会导致刷新,追加也会刷新( flush ();)
    }
}

字节流转化为字符流

public class Demo11 {
    public  static <ReaderInputStream> void  main(String[]args) throws IOException {
        FileInputStream frs = new FileInputStream ("d://f.txt");
        //将字节输入流,转换为字符输入流
        //参数1,要转换的字节流
        //参数2,指定的编码格式
        InputStreamReader isr = new InputStreamReader (frs,"UTF-8");
        while(true){
            int c =isr.read ();
            if(c ==-1){
                break;
            }
            System.out.println ((char)c);
        }
    }
}
public class Demo12 {
    public  static <ReaderInputStream> void  main(String[]args) throws IOException {
        FileOutputStream frs = new FileOutputStream ("d://f.txt",true);
        OutputStreamWriter  oew = new OutputStreamWriter (frs);
        oew.write ("充电电池的懊恼");
        oew.flush ();
        oew.close ();
    }

}

Print 与BuffereReader

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pY4yJ5ch-1595864645306)(C:\Users\hu\AppData\Roaming\Typora\typora-user-images\1595845425613.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xtkJw1Nx-1595864645312)(C:\Users\hu\AppData\Roaming\Typora\typora-user-images\1595845580632.png)]

收集异常日志

public class Demo13 {
    public  static <ReaderInputStream> void  main(String[]args){
        try {
            String s = null;
            s.toString ();
        }catch ( Exception e) {
            e.printStackTrace ();//打印到控制台
        }

    }

}
//打到文件夹
public class Demo13 {
    public  static <ReaderInputStream> void  main(String[]args) throws FileNotFoundException {
        try {
            String s = null;
            s.toString ();
        }catch ( Exception e) {
            PrintWriter pw  = new PrintWriter ("d://f.txt");
            SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd HH:mm:zz");
            pw.println (sdf.format (new Date ()));
            e.printStackTrace (pw);
            pw.close ();
            e.printStackTrace ();


        }

    }

}

Properties(extends Hasmap)

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

//        Properties ppt = new Properties ();
//        ppt.put ("name","金苹果");
//        ppt.put ("info","讲述了苹果种植的过程");
//        FileWriter fw = new FileWriter ("d://Book.properties");
//        ppt.store (fw,"存储的图书");
//        fw.close ();
        Properties ppt = new Properties ();
        FileReader  fe = new FileReader ("d://Book.properties");
        ppt.load (fe);
        System.out.println (ppt.getProperty ("name"));
        System.out.println (ppt.getProperty("info"));


    }

}

序列化 反序列化

序列化 :将创建对象以文件形式存储起来,

反序列化:把文件对象载到程序,读取

public class Book {

    public static void  main(String []args) throws IOException, ClassNotFoundException {
        //序列化
        /*Booktext  b = new Booktext ("金苹果","描述苹果种植的过程");
        ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("D://Book.txt"));
       oos.writeObject (b);
       oos.close ();*/
        //反序列化
        ObjectInputStream fe = new ObjectInputStream (new FileInputStream ("D://Book.txt"));
        Object o = fe.readObject ();
        System.out.println (o);

    }

    static class Booktext implements Serializable { //只是为了申明是他的子类,没有重写任何方法
        private String name; //属性也都必须实习Serializable
        private String info;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }

        public Booktext() {

        }

        public Booktext(String name, String info) {
            this.name = name;
            this.info = info;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "name='" + name + '\'' +
                    ", info='" + info + '\'' +
                    '}';
        }
    }
}

try -with -resources

public class Demo15 {//jdk1.7
    public  static  void  main(String[]args) throws IOException {
            try(FileReader fr = new FileReader ("d://book.txt")) {//继承CLoseable类(close())
                int c = fr.read ();
                System.out.println ((char) c);

            }catch (IOException e) {
                e.printStackTrace ();
            }
       //  JDK1.9
        FileReader fr = new FileReader ("d://book.txt");
        PrintWriter pw = new PrintWriter ("d://book.txt");
        try(fr;pw){
            int c = fr.read ();
            System.out.println ((char) c);
        }catch (IOException e) {
            e.printStackTrace ();
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

IO流作业 的相关文章

随机推荐

  • 智能教育装备法则

    二十一世纪 在互联网 大数据 智慧教育等新科技的带动下 我国教育信息化教育信息化产业规模将以每年平15 的速度增长 格物斯坦表示 有越来越多智能教育装备的后起之秀企业开启了他们的研发软件和硬件的能力 教育的信息化首先是教育装备的信息化和智慧
  • 浅析瀑布流布局及其原理

    一 什么是瀑布流 瀑布流 又被称作为瀑布流式布局 是一种比较流行的网站页面布局方式 视觉表现为参差不齐的多栏布局 随着页面滚动条向下滚动 这种布局还会不断加载数据块并附加至当前尾部 这种布局方式常见于一些图片为主的网站 为什么要使用瀑布流
  • 关于QT5.12.0在VS2019上使用的细节

    关于QT5 12 0在VS2019上的使用细节 博主使用的版本 QT5 12 0 VS2019 其他Qt版本同样适用 1 添加Qt的环境变量 在Win10下 编辑系统环境变量 环境变量 Path 新建添加Qt的bin目录路径 D QT 12
  • Burpsuite Professional 2023.6.2 最新版安装教程

    更新时间 2023年07月23日11 47 48 本文以mac为例 Windows上方法是类似的 1 缘由 因为我用的Burpsuite版本有点老 导致有时候给人培训的时候 面对新版Burpsuite一脸懵逼 很多操作都不太一样 所以这次直
  • 从零开始 verilog 以太网交换机(七)总结与展望

    从零开始 verilog 以太网交换机 七 总结与展望 声明 博主主页 王 嘻嘻的CSDN主页 从零开始 verilog 以太网交换机系列专栏 点击这里 未经作者允许 禁止转载 侵权必删 关注本专题的朋友们可以收获一个经典交换机设计的全流程
  • Trinitycore学习之在vscode查看远端服务器上源码配置

    1 安装vscode 去官网下载 这里下载windows版本安装包 zip https code visualstudio com Download 2 安装后 安装扩展chinese 使用中文设置 需要重启vscode 3 安装ssh相关
  • 报错:‘wget‘ 不是内部或外部命令,也不是可运行的程序

    在jupyter lab下使用wegt 导入需要用到的数据集 wget https tianchi media oss cn beijing aliyuncs com DSW 7XGBoost train csv wget 不是内部或外部命
  • 终端zsh_只需七个步骤,即可使您的“ ZSH”终端站起来—直观指南

    终端zsh by rajaraodv 通过rajaraodv 只需七个步骤 即可使您的 ZSH 终端站起来 直观指南 Jazz Up Your ZSH Terminal In Seven Steps A Visual Guide In th
  • 设置PHP的fpm的系统性能参数pm.max_children

    1 介绍 PHP从Apache module换成了Fpm 跑了几天突然发现网站打不开了 页面显示超时 检查MySQL Redis一众服务都正常 进入Fpm容器查看日志 发现了如下的错误信息 server reached pm max chi
  • day05 java_Spring IoC 和 DI

    为什么使用spring框架 1 解耦代码 每次使用都要new一个对象 2 解决事务繁琐问题 创建对象 初始化 调用方法 销毁对象 3 使用第三方框架麻烦的问题 总结 spring是一个轻量级的Ioc Di和AOP容器 轻量级 简洁 高效 低
  • 面试官偷偷给到45k*16薪,堪称面试风向标!

    前天加完班 回家路上翻了下粉丝群 发现群里最近在疯传一份叫 前端offer收割机养成指南 的资料 本来感觉这个title看起来有点离谱 结果没想到仔细一看 这份资料竟然真的有点东西 内容收纳的很全 而且融合了很多今年的新玩意 据我所知有人靠
  • HTML 整体缩放

    最近用到web 控件加载网页需要缩放问题 由于控件比较旧 所以只能从html 入手 html 页面缩放主要有两种 IE 可使用 CSS body zoom 1 2 或者微软相关的控件支持 包括BCB 其它 浏览器可使用 body trans
  • 指针字符串 与 const char * 即const * char 的详细使用讲解

    指针字符串的使用问题 一 直接定义字符串指针的使用注意事项 定义字符串指针的时候 const char 和字符串本身相同 就不会出现警告 const char char const 作用 const char p 表示的是指针p指向的数值不
  • Kubernetes CoreDNS 状态是 CrashLoopBackOff 报错

    查看状态的时候 遇见coredns出现crashlookbackoff 首先我们来进行排错 不管是什么原因 查看coredns的详细信息 以及logs root k8s master coredns kubectl get pod svc
  • Shell 中 &>/dev/null 和 >/dev/null 2>&1

    下面 咱们一起来看看这个命令操作涉及到的知识点 这其实涉及到三部分的内容 如下图 1 文件描述符 linux shell脚本攻略 的描述 文件描述符是与文件输入 输出关联的整数 它们用来跟踪已打开的文件 最常见的文件描述符是 stidin
  • linux cuda安装目录,Ubuntu 11.10上安装CUDA开发环境的方法及命令

    这篇文章全部内容在我的ThinkPad W520 Ubuntu 11 10 x64位上测试通过 但不代表这篇文章的内容适合你 任何根据这篇文章操作产生的后果 这篇文章作者cheungmine概不负责 英文参考文档 http develope
  • 华为OD机试 C++ [周末爬山]

    题目 小明打算周末去爬山 有一份山的地图 上面用数字表示山的高度 0表示平地 1至9表示不同的山峰高度 小明每次移动只能上下左右移动一格 并且山峰高度差不能超过k 现在他从地图的左上角出发 你能帮他找出他能爬到的最高的山峰是多高吗 还有 他
  • Android数据存储 —— SharedPreferences

    SharedPreferences以键值对的形式存储数据 支持几种基本数据类型 boolean float int long String 一般存储配置信息 它保存的数据时持久化的 即使应用被关掉也不会丢失 存储格式为 xml 一般放在内部
  • 三十二、java版 SpringCloud分布式微服务云架构之Java LinkedList

    Java LinkedList 链表 Linked list 是一种常见的基础数据结构 是一种线性表 但是并不会按线性的顺序存储数据 而是在每一个节点里存到下一个节点的地址 链表可分为单向链表和双向链表 一个单向链表包含两个值 当前节点的值
  • IO流作业

    io 文件操作 in 读取 out 写出 java io File 常用的三个构造方法 File String pathname 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例 public class Demo01 pu