一、什么是IO流

输入流和输出流。

  • 输入流:数据从数据源(文件)到程序(内存)的路径
  • 输出流:数据从程序(内存)到数据源(文件)的路径

二、常用的文件操作

学习目标:创建文件对象相关构造器和方法

new File(String pathname)//根据路径构建一个File对象

new File(File parent,String child)//根据父目录文件 子路径构建

new File(String parent,String child)//根据父目录 子路径构建

学习任务:在e盘下,创建文件news1.txt、news2.txt、news3.txt用三种不同方式创建。

三种方式简单看一下就行,后面会经常遇到。

new File(String pathname)//根据路径构建一个File对象

package com.file;
import java.io.*;
public class FileCreate {
    public static void main(String[] args) {
            //方式 1 new File(String pathname)
            String filePath = "e:\\news1.txt";
            File file = new File(filePath);
            try {
                //创建新文件
                file.createNewFile();
                System.out.println("文件创建成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

new File(File parent,String child)//根据父目录文件 子路径构建

package com.file;
import java.io.*;
public class FileCreate {
    public static void main(String[] args) {
        //方式 2 new File(File parent,String child) //根据父目录文件 子路径构建
        //e:\\news2.txt
            File parentFile = new File("e:\\");
            String fileName = "news2.txt";
           //这里的 file 对象,在 java 程序中,只是一个对象
           //只有执行了 createNewFile 方法,才会真正的,在磁盘创建该文件
            File file = new File(parentFile, fileName);
            try {
                file.createNewFile();
                System.out.println("创建成功~");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

new File(String parent,String child)//根据父目录 子路径构建

package com.file;
import java.io.*;
public class FileCreate {
    public static void main(String[] args) {
        //方式 3 new File(String parent,String child) //根据父目录 子路径构建
            String parentPath = "e:\\";
            String fileName = "news3.txt";
            File file = new File(parentPath, fileName);
            try {
                file.createNewFile();
                System.out.println("创建成功~");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

三、获取文件的相关信息

getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory

学习任务:获取文件的大小、文件名、路径、父File,是文件还是目录(目录本质也是文件,一种特殊的文件),是否存在

四、目录的操作和文件删除

学习任务:

  • 判断e:\news1.txt是否存在,如果存在就删除
  • 判断e:\\demo02是否存在,存在就删除,否则提示不存在
  • 判断e:\\demo\a\b\c目录是否存在,如果存在就提示已经存在,否则就创建
package com.collection;
import java.io.File;
public class Delete {
    public static void main(String[] args) {
        String filePath="e:\\news1.txt";
        File file=new File(filePath);
        if(file.exists()){
            file.delete();
        }else {
            System.out.println("否则文件不存在~");
        }
    }
}
package com.collection;
import java.io.File;
public class Delete {
    public static void main(String[] args) {
        String filePath="e:\\demo02";
        File file=new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println(filePath "删除成功");
            }
            else{
                System.out.println(filePath "删除失败");
            }
        }else {
            System.out.println("否则目录不存在~");
        }
    }
}
package com.collection;
import java.io.*;
public class Delete {
    public static void main(String[] args) {
        String directoryPath="e:\\demo\\a\\b\\c";
        File file=new File(directoryPath);
        if(file.exists()) {
            System.out.println(directoryPath   "存在。。");
        }
        else {
            if (file.mkdirs()){
                System.out.println(directoryPath "创建成功。。");
            }else{
                System.out.println(directoryPath "创建失败。。");
            }
        }
    }
}

按操作数据单位不同分为:字节流(8bit)二进制文件,字符流(按字符)文本文件

按数据流的流向不同分为:输入流,输出流

按流的角色的不同分为:节点流,处理流/包装流

字节流:InputStream,OutputStream

字符流:Reader,Writer

五、IO流体系图-常用的类

六、FileInputStream常用方法

学习任务:请使用 FileInputStream 读取 hello.txt 文件,并将文件内容显示

先在e盘下创建hello.txt输入内容hello world

package com.FileInputStream;
import java.io.FileInputStream;
import java.io.IOException;
//字节流文件的输入程序
public class FileInputStream_ {
    public static void main(String[] args) {
        String filePath="e:\\hello.txt";
        int readData=0;
        FileInputStream fileInputStream=null;
        try {
            //创建 FileInputStream 对象,用于读取文件
            fileInputStream=new FileInputStream(filePath);
            //从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
            //如果返回-1 , 表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char)readData);//转成 char 显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭文件流
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

七、FileOutputStream常用方法

学习任务:请使用 FileOutputStream 在 abc.txt 文件,中写入 “hello,world”. 如果文件不存在,会创建 文件(注意:前提是目录已经存在.)

package com.hspedu.outputstream_;
import java.io.*;
public class FileOutputStream01 {
    public static void main(String[] args) {
        String filePath = "D:\\abc.txt";
        FileOutputStream fileOutputStream = null;
        try {
            //得到 FileOutputStream 对象 对象
            //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
            // 2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath);
            //写入一个字节
            //fileOutputStream.write('H');
            //写入字符串
            String str = "hello,world!";
            //str.getBytes() 可以把 字符串-> 字节数组
            //fileOutputStream.write(str.getBytes());
            /*
             write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
             */
            fileOutputStream.write(str.getBytes(), 0, 3);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

学习任务:编程完成图片/音乐 的拷贝

package com.hspedu.outputstream_;
import java.io.*;
public class FileCopy {
    public static void main(String[] args) {
        String srcFilePath="e:\\9030.jpg";
        String destFilePath="e:\\9031.jpg";
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
            fileInputStream=new FileInputStream(srcFilePath);
            fileOutputStream=new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效果
            byte[] buf=new byte[1024];
            int readLen=0;
            while ((readLen=fileInputStream.read(buf))!=-1){
                fileOutputStream.write(buf,0,readLen);
            }
            System.out.println("拷贝成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(fileInputStream!=null){
                    fileInputStream.close();
                }
                if(fileOutputStream!=null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

八、FileReader常用方法

  • new FileReader(File/String)
  • read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
  • read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1
  • 相关API:
  • new String(char[]):将char[]转换成String
  • new String(char[],off,len):将char[]的指定部分转换成String

九、FileWriter常用方法

  • new FileWriter(File/String):覆盖模式,相当于流的指针在首端
  • new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
  • write(int):写入单个字符
  • write(char[]):写入指定数组
  • write(char[],off,len):写入指定数组的指定部分
  • write(string):写入单个字符
  • write(string[],off,len):写入字符串的指定部分
  • 相关API:String类:toCharArray:将String转换成char[]
  • FileWriter使用后,必须要关闭(close)或刷新(flush), 否则写入不到指定的文件!

学习任务:使用 FileReader 从 story.txt ,这一步先在story.txt存在数据,然后在端口输出数据显示出来

package com.reader_;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile01 {
    public static void main(String[] args) {
        String filePath="e:\\story.txt";
        FileReader fileReader=null;
        int data=0;
        //创建FileReader对象
        try{
            fileReader =new FileReader(filePath);
            //循环读取 使用 read, 单个字符读取
            while((data=fileReader.read())!=-1){
                //data数值为整数型,强制转换为字符
                System.out.print((char)data);
            }
        }catch(
                IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(fileReader!=null){
                    //关闭文件流
                    fileReader.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

学习任务:字符数组读取文件

package com.reader_;
import java.io.FileReader;
import java.io.IOException;
public  class ReadFile02 {
    public static void main(String[] args) {
        String filePath="e:\\story.txt";
        FileReader fileReader=null;
        int readLen=0;
        char[] buf=new char[8];
        //创建FileReader对象
        try{
            fileReader =new FileReader(filePath);
            //循环读取 使用 read(buf), 返回的是实际读取到的字符数
            //如果返回-1, 说明到文件结束
            while((readLen=fileReader.read(buf))!=-1){
                System.out.print(new String(buf,0,readLen));
            }
        }catch(
                IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(fileReader!=null){
                    fileReader.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

学习任务:使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中

package com.hspedu.writer_;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriter_ {
    public static void main(String[] args) {
        String filePath="e:\\noth.txt";
        FileWriter fileWriter=null;
        char[] chars={'a','b','c'};
        try {
            fileWriter = new FileWriter(filePath);
            //3) write(int):写入单个字符
            fileWriter.write('H');
            // 4) write(char[]):写入指定数组
            fileWriter.write(chars);
            // 5) write(char[],off,len):写入指定数组的指定部分
            fileWriter.write("程序员飞鸟".toCharArray(), 0, 3);
            // 6) write(string):写入整个字符串
            fileWriter.write(" 你好广州");
            fileWriter.write("风雨之后,定见彩虹");
            // 7) write(string,off,len):写入字符串的指定部分
            fileWriter.write("上海天津", 0, 2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                //对应 FileWriter , 一定要关闭流,或者 flush 才能真正的把数据写入文件里面
                fileWriter.flush();//关闭文件流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("程序结束~");
    }
}

到此这篇关于Java细数IO流基础到方法使用的文章就介绍到这了,更多相关Java IO流内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Java细数IO流底层原理到方法使用的更多相关文章

  1. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  3. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  4. Java实现世界上最快的排序算法Timsort的示例代码

    Timsort 是一个混合、稳定的排序算法,简单来说就是归并排序和二分插入排序算法的混合体,号称世界上最好的排序算法。本文将详解Timsort算法是定义与实现,需要的可以参考一下

  5. Java日期工具类的封装详解

    在日常的开发中,我们难免会对日期格式化,对日期进行计算,对日期进行校验,为了避免重复写这些琐碎的逻辑,我这里封装了一个日期工具类,方便以后使用,直接复制代码到项目中即可使用,需要的可以参考一下

  6. Java设计模式之模板方法模式Template Method Pattern详解

    在我们实际开发中,如果一个方法极其复杂时,如果我们将所有的逻辑写在一个方法中,那维护起来就很困难,要替换某些步骤时都要重新写,这样代码的扩展性就很差,当遇到这种情况就要考虑今天的主角——模板方法模式

  7. Java 中 Class Path 和 Package的使用详解

    这篇文章主要介绍了Java 中 Class Path和Package的使用详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

  8. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  9. Java一维数组和二维数组元素默认初始化值的判断方式

    这篇文章主要介绍了Java一维数组和二维数组元素默认初始化值的判断方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  10. java实现emqx设备上下线监听详解

    这篇文章主要为大家介绍了java实现emqx设备上下线监听详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部