服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java细数IO流底层原理到方法使用

Java细数IO流底层原理到方法使用

2022-11-07 11:48程序员飞鸟 Java教程

IO主要用于设备之间的数据传输,Java将操作数据流的功能封装到了IO包中,这篇文章主要给大家介绍了关于Java新手学习之IO流简单使用的相关资料,需要的朋友可以参考下

一、什么是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对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)//根据父目录文件+子路径构建

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)//根据父目录+子路径构建

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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,是文件还是目录(目录本质也是文件,一种特殊的文件),是否存在

Java细数IO流底层原理到方法使用

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

学习任务:

  • 判断e:\news1.txt是否存在,如果存在就删除
  • 判断e:\\demo02是否存在,存在就删除,否则提示不存在
  • 判断e:\\demo\a\b\c目录是否存在,如果存在就提示已经存在,否则就创建
?
1
2
3
4
5
6
7
8
9
10
11
12
13
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("否则文件不存在~");
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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("否则目录不存在~");
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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流体系图-常用的类

Java细数IO流底层原理到方法使用

六、FileInputStream常用方法

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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”. 如果文件不存在,会创建 文件(注意:前提是目录已经存在.)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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();
            }
        }
    }
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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存在数据,然后在端口输出数据显示出来

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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();
            }
        }
    }
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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 文件中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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流内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/A6_107/article/details/124785253

延伸 · 阅读

精彩推荐
  • Java教程Elasticsearch 映射参数详解 fields

    Elasticsearch 映射参数详解 fields

    这篇文章主要介绍了fields Elasticsearch 映射参数fields,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    小黑王HK5022021-10-06
  • Java教程Java模拟实现ATM机

    Java模拟实现ATM机

    这篇文章主要为大家详细介绍了Java模拟实现ATM机,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    点丶错了。。11282021-08-27
  • Java教程Java中的泛型

    Java中的泛型

    这篇文章主要介绍为何要泛型,如何使用泛型,自定义泛型的方法,泛型类的子类等多方面介绍了JAVA中的泛型,需要的小伙伴请看下文...

    小蜗牛耶9592021-12-10
  • Java教程浅谈JAVA内存分配与参数传递

    浅谈JAVA内存分配与参数传递

    这篇文章主要介绍了JAVA内存分配与参数传递,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着...

    Hola World11572021-07-24
  • Java教程springboot 如何配置多个jndi数据源

    springboot 如何配置多个jndi数据源

    这篇文章主要介绍了springboot 如何配置多个jndi数据源的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    UziNb6512021-10-22
  • Java教程java中hibernate二级缓存详解

    java中hibernate二级缓存详解

    本篇文章中主要介绍了java中hibernate二级缓存详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    SIHAIloveYAN3592020-09-25
  • Java教程Spring Boot DevTools 全局配置学习指南

    Spring Boot DevTools 全局配置学习指南

    这篇文章主要介绍了Spring Boot DevTools 全局配置,注意包括直接重启项目与devtools重启的区别,DevTools配置,DevTools全局配置及trigger-file控制重启行为的相关知识...

    泠青沼~4972022-10-31
  • Java教程JAVA中JNI的简单使用分享

    JAVA中JNI的简单使用分享

    这篇文章介绍了JAVA中JNI的简单使用,有需要的朋友可以参考一下 ...

    java技术网4422019-10-15