前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IO与文件「建议收藏」

IO与文件「建议收藏」

作者头像
全栈程序员站长
发布2022-09-21 08:26:55
2150
发布2022-09-21 08:26:55
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

IO与文件

File

File类的一个对象,代表一个文件或一个文件目录(俗称文件夹)

代码语言:javascript
复制
package com.atguigu.java;

import java.io.File;
import java.io.IOException;

public class FileTest { 
   
    public static void main(String[] args) throws IOException { 
   
        File file1 = new File("hello.txt");//相对路径,相对当前module
        System.out.println(file1.getAbsoluteFile());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(file1.lastModified());


        String[] list = file1.list();
        for(String s: list){ 
   
            System.out.println(list);
        }
        File[] files = file1.listFiles();
        for(File f:files){ 
   
            System.out.println(files);
        }
        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.isHidden());

        if(!file1.exists())
            file1.createNewFile();
        else { 
   
            file1.delete();
        }
        file1.mkdir();
        file1.mkdirs();
    }
}

File类中涉及到关于文件或文件目录的创建,删除,重命名,修改时间,文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。

流的分类

  • 字节流,字符流
  • 输入流,输出流
  • 节点流,处理流

流的体系

在这里插入图片描述
在这里插入图片描述

缓冲流

关闭流的时候先关闭外面的,再关闭里面的。(关闭外层流的时候,内层流也会自动的关闭) 缓冲流读写速度更快。读写会在内存中开辟一块儿空间。

转换流

提供了字节流和字符流之间的转换

  • InputStreamReader
  • OutputStreamWriter 实例:utf-8文件转化为gbk文件
代码语言:javascript
复制
package com.atguigu.java;

import java.io.*;

public class HelloWorld { 
   
    public static void main(String[] args) throws IOException { 
   
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_bgk.txt");

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);

        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

        char[] cbuf = new char[20];

        int len;
        while ((len = isr.read(cbuf)) != -1){ 
   
            osw.write(cbuf,0,len);
        }
        isr.close();
        osw.close();


    }
}

标准输入输出流

  1. 标准的输入输出流 System,in 标准的输入流,默认从键盘输入,类型是InputStream System,out 标准的输出流,默认从控制台输出,类型是 PrintStream,其是OutputStream的子类
  2. System类的SetIn()/Setout()方式重新指定输入和输出流
  3. 练习:从键盘输入字符串,要求读取到的整行字符串转换成大写输出、然后继续进行输入操作
代码语言:javascript
复制
package com.atguigu.java;

import java.io.*;

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

        InputStreamReader isr = new InputStreamReader(System.in);

        BufferedReader br = new BufferedReader(isr);
        String data;
        while(true){ 
   
            data = br.readLine();
            if("e".equals(data) || "exit".equals(data))
                break;
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
        br.close();


    }
}

打印流

PrintStream和PrinterWriter提供了一系列重载方法print()和println() 将System.out.println()方法打印到指定文件

代码语言:javascript
复制
package com.atguigu.java;

import java.io.*;

public class HelloWorld { 
   
    public static void main(String[] args) throws IOException { 
   
        PrintStream ps = null;
        try { 
   
            FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
            ps = new PrintStream(fos,true);
            if(ps != null){ 
   
                System.setOut(ps);
            }

            for(int i = 0;i <= 255;i ++){ 
   
                System.out.println((char)i);
                if(i % 50 == 0)
                    System.out.println();
            }

        }catch (Exception e){ 
   
            ps.close();
        }

    }
}

数据流

DataInputStream和DataOutputStream

代码语言:javascript
复制
package com.atguigu.java;

import java.io.*;

public class HelloWorld { 
   
    public static void main(String[] args) throws IOException { 
   
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("刘建辰");
        dos.flush();
        dos.writeInt(23);
        dos.writeBoolean(true);
        dos.flush();
        dos.close(); 
    }
}

对象流

ObjectInputStream和ObjectInputStream 对象要想可序列化,对象类必须实现Serializable接口 作用:可以把java中的对象写入到数据源中, 也能把对象从数据源中还原回来 该对象必须指定静态类型常量serialVersionUID static和transient修饰的属性不能被序列化

代码语言:javascript
复制
package com.atguigu.java;

import java.io.*;

public class HelloWorld { 
   
    public static void main(String[] args){ 
   
        ObjectOutputStream oos = null;
        try { 
   
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();
        }catch (IOException e){ 
   
            e.printStackTrace();
        }finally { 
   
            if(oos != null)
            { 
   
                try { 
   
                    oos.close();
                } catch (IOException e) { 
   
                    e.printStackTrace();
                }
            }
        }


        ObjectInputStream ois = null;
        try { 
   
            ois = new ObjectOutputStream(new FileInputStream("object.dat"));
            Object object = ois.readObject();
            String str = (String)object;
        } catch (IOException e) { 
   
            e.printStackTrace();
        } catch (ClassNotFoundException e) { 
   
            e.printStackTrace();
        } finally { 
   
            if(ois != null) { 
   
                try { 
   
                    ois.close();
                } catch (IOException e) { 
   
                    e.printStackTrace();
                }
            }
        }
    }
}

RandomAccessFile类

  1. RandomAccessFile 直接继承于Object类,实现了 DataInput和DataOutput接口
  2. RandomAccessFile 既可以作为一个输入流,又可以作为一个输出流
  3. “r”以只读方式打开 “rw”打开以便读取和写入 “rwd”打开以便读取和写入:同步文件内容的更新 “rws”打开以便读取和写入:同步文件内容和元数据的更新
  4. 如果RandomAcessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建,如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/168827.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • IO与文件
    • File
      • 流的分类
        • 流的体系
          • 缓冲流
          • 转换流
          • 标准输入输出流
          • 打印流
          • 数据流
          • 对象流
          • RandomAccessFile类
      相关产品与服务
      文件存储
      文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档