zoukankan      html  css  js  c++  java
  • JavaWeb入门(四) I-O

    JavaWeb入门(四) I/O

    标签(空格分隔): JavaWeb


    原文地址

    File类

    File 类是 I/O 操作中最常用的类。它的常用方法有:

    exists() 文件是否存在
    isFile() 是否是文件
    isDirectory() 是否是目录
    createNewFile() 创建文件
    delete() 删除文件或空文件夹
    renameTo(File dest) 重命名,可以是不同目录,但不能是不同盘符
    mkdir() 创建单级文件夹
    mkdirs 可创建多级文件夹

    文件属性的读取和设置:

    file.length() 文件的大小,单位:byte
    file.getParent() 父目录的相对路径
    file.getAbsolutePath() 文件的绝对路径

    例:如何得到父级目录的绝对路径

     String parentAbsPath = new File(file.getAbsolutePath()).getParent();

    canWrite() 文件可写性
    canRead() 文件可读性
    setReadable(true) 设置文件为可读
    setWritable(false) 设置文件为不可写

    文件的简单读写

    读取方式
    1. FileInputStream 文件数据输入为字节流
    2. InputStreamReader 字节流到字符流的桥梁,从名称中也能看出这是InputStreamReader
    3. BufferedReader 读取字符流的缓冲区。

    例:

    public static void readFile(String _fileName) throws IOException {
    
            FileInputStream fis = new FileInputStream(_fileName);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String str;
            while ((str = br.readLine()) != null){
                System.out.println(str);
            }
    
            br.close(); //先关闭后打开的
            isr.close();
            fis.close();
    
        }

    写入方式:
    1. FileOutputStream 文件数据输出为字节流
    2. OutputStreamWriter 字符流与字节流的桥梁
    3. BufferedWriter 写入字符流缓冲区

    字符流与字节流的区别

    字节流通常以Stream 结尾,如文字,图片,流媒体(音视频),字节流以字节为单位对文件或其他输入进行读取。
    字符流通常以Reader, Writer 结尾,它只能处理文本类型数据,它每次读取一个或多个字节,在去查询指定编码表如UTF-8然后返回字符。

    如何使用字节流进行数据的读写?

    利用FileInputStreamread()FileOutputStreamwrite 方法。

    例:

        //字节流的读取
        public static void readInputStream(String _fileName) throws IOException {
    
            FileInputStream fis = new FileInputStream(_fileName);
            byte[] bytes = new byte[4]; //用来存放字节流
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            int length = 0;
            while ((length =fis.read(bytes)) != -1){
                bos.write(bytes, 0, length);
    
            }
            System.out.println(new String(bos.toByteArray(), "utf-8"));
            fis.close();
        }
        //字节流的写入
        public static void writeOutputStream(String _fileName) throws IOException {
    
            FileOutputStream fos = new FileOutputStream(_fileName);
            fos.write("武都头,您里面请!".getBytes("utf-8"));
        }
    

    注:

    • 这里是利用FileInputStreamread() 的方法直接读入一个byte 数组中,然后再将这个byte 数组转为字符串。
    • 这个length 是非常重要的,它记录了每次实际读入byte 数组中的字节个数。如何不考虑这点,可能会产生乱码。
    • 同理,可利用FileOutputStreamwrite() 的方法写入一个byte 数组。

    直接使用字符流进行读写

    上面的例子我们是通过字节流的方式进去读取的,然后将读取的字节数组转为字符串。而借助InputStreamReaderOutputStreamWriter 我们可以直接读取字符流。

        //字符流的读取
        public static void readByInputStreamReader(String _fileName) throws IOException {
    
            FileInputStream fis = new FileInputStream(_fileName);
            InputStreamReader isr = new InputStreamReader(fis, "utf-8");
    
            StringBuilder sb = new StringBuilder();
            char[] charBuffer = new char[100];
            int l = 0;
    
            while ((l = isr.read(charBuffer)) != -1) {
                sb.append(new String(charBuffer, 0, l));
            }
    
            System.out.println(sb);
        }
        //字符流的写入 略

    实际开发

    在实际开发中,有许多优秀的I/O 库供我们使用,我们因此无需重复造轮子。
    如: Apache.org 下 的commons包提供了对I/O 操作的封装。
    因此: 学会使用第三方库可以大大提高我们的开发效率。

    例:读取指定目录下的某种文件

    public class GetMp3List {
    
        public static void main(String[] args) {
            listFiles("E:\JavaWeb@JKXY", ".pdf");
        }
    
        public static void listFiles(String _filePath, String suffix) {
            File dir = new File(_filePath);
            File[] files = dir.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        listFiles(f.getAbsolutePath(), suffix);
                    }
                    if (f.getName().endsWith(suffix)) {
                        System.out.println(f.getName());
                    }
                }
            }
        }
    }

    输出结果示例:

    23种设计模式 - v1.1.pdf
    Eclipse 使用教程 - v1.0.pdf
    IntelliJ_IDEA13基础教程.pdf
    Java 中文乱码解决之道 - v1.0.pdf
    Java 语言快速入门 - v1.0.pdf
    Java 集合学习指南 - v1.1.pdf
    MySQL 中文版 - v1.0.pdf
    [MySQL核心技术手册(第二版)].(美)戴尔.扫描版.pdf
    [算法(第四版).中文版.图灵程序设计丛书]Algorithms.-.Fourth.Edition.谢路云.影印版(高清)[www.ed2kers.com].pdf
    《汪曾祺全集+3+散文卷》_北京师范大学出版社+19.pdf
    《汪曾祺全集.1.小说卷》.pdf
    书读完了 金克木.pdf
    自然码双拼速成教学.pdf
    ._鲜花订购系统概要设计.pdf
    鲜花订购系统概要设计.pdf
    ._商场VIP消费情况查询系统.pdf
    商场VIP消费情况查询系统.pdf
    Head First HTML与CSS、XHTML(中文版).pdf
    javascript 权威指南(第6版).pdf
    Java程序员面试宝典.pdf
    Java面试宝典2016版.pdf

  • 相关阅读:
    【Azure 应用服务】由 Azure Functions runtime is unreachable 的错误消息推导出 ASYNC(异步)和 SYNC(同步)混用而引起ThreadPool耗尽问题
    【Azure API 管理】是否可以将Swagger 的API定义导入导Azure API Management中
    【Azure 应用服务】Azure Function 不能被触发
    【Azure 环境】Azure Key Vault (密钥保管库)中所保管的Keys, Secrets,Certificates是否可以实现数据粒度的权限控制呢?
    【Azure 事件中心】为应用程序网关(Application Gateway with WAF) 配置诊断日志,发送到事件中心
    【Azure 事件中心】azure-spring-cloud-stream-binder-eventhubs客户端组件问题, 实践消息非顺序可达
    【Azure API 管理】Azure API Management通过请求中的Path来限定其被访问的频率(如1秒一次)
    【Azure 环境】前端Web通过Azure AD获取Token时发生跨域问题(CORS Error)
    【Azure 应用服务】记一次Azure Spring Cloud 的部署错误 (az spring-cloud app deploy -g dev -s testdemo -n demo -p ./hellospring-0.0.1-SNAPSHOT.jar --->>> Failed to wait for deployment instances to be ready)
    【Azure 应用服务】App Service中抓取 Web Job 的 DUMP 办法
  • 原文地址:https://www.cnblogs.com/mrbourne/p/9959436.html
Copyright © 2011-2022 走看看