如何快速了解Java中的IO流

发布时间:2021-10-26 10:12:48 作者:iii
来源:亿速云 阅读:304

这篇文章主要介绍“如何快速了解Java中的IO流”,在日常操作中,相信很多人在如何快速了解Java中的IO流问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何快速了解Java中的IO流”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一. File类
1.简单介绍

2.基本用法
在文件系统中,每个文件都存放在一个目录下。绝对文件名( absolute file name) 是由文件名和它的完整路径以及驱动器字母组成。相对文件名是相对于当前工作目录的。例如,c:\book\Welcome.java 是文件Welcome.java 在 Windows 操作系统上的绝对文件名。Welcome.java 是一个相对文件名。

windows和DOS系统默认使用“\”来表示 UNIX和URL使用“/”来表示 Java程序支持跨平台运行,因此路径分隔符要慎用。为了解决这个隐患,File类提供了一个常量: public static final String separator。根据操作系统,动态的提供分隔符。 File file = new File("D:"+File.separator +"JavaSE"+File.separator +"JavaProject");

2.1 构造方法

//构造器一 :public File(String pathname)    File file1 = new File("hello.txt");//相对路径    File file2 = new File("D:\\JavaSE\\JavaProject\\WorkSpace\\ioDemo\\hi.txt");//绝对路径    System.out.println(file1);    System.out.println(file2);    //构造器二:public File(String parent,String child)    File file3 = new File("D:\\JavaSE", "JavaProject");    System.out.println(file3);    //构造器三:public File(File parent,String child)    File file4 = new File(file3, "he.txt");    System.out.println(file4);

输出结果:

如何快速了解Java中的IO流

2.2 常用方法
2.2.1 File类的获取功能

 @Test     public void test4() {         File file1 = new File("hello.txt");//不存在,只是一个对象         File file2 = new File("D:\\io\\hi.txt");//在硬盘存在          System.out.println(file1.getAbsolutePath());         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());          System.out.println("*************************************");          System.out.println(file2.getAbsolutePath());         System.out.println(file2.getPath());         System.out.println(file2.getName());         System.out.println(file2.getParent());         System.out.println(file2.length());         System.out.println(file2.lastModified());     } 复制代码

输出结果:

如何快速了解Java中的IO流

2.2.2 File类的判断功能

 @Test     public void test5(){         File file1 = new File("hello.txt");//在硬盘中真实存在         File file2 = new File("hello1.txt");//不真实存中         System.out.println(file1.isDirectory());         System.out.println(file1.isFile());         System.out.println(file1.exists());         System.out.println(file1.canRead());         System.out.println(file1.canWrite());         System.out.println(file1.isHidden());          System.out.println("*****************************");          System.out.println(file2.isDirectory());         System.out.println(file2.isFile());         System.out.println(file2.exists());         System.out.println(file2.canRead());         System.out.println(file2.canWrite());         System.out.println(file2.isHidden());         System.out.println("*********************************");          File file3 = new File("d:\\io");//真实存在         File file4 = new File("d:\\io1");//不存在         System.out.println(file3.isDirectory());         System.out.println(file3.isFile());         System.out.println(file3.exists());         System.out.println(file3.canRead());         System.out.println(file3.canWrite());         System.out.println(file3.isHidden());          System.out.println("*****************************");          System.out.println(file4.isDirectory());         System.out.println(file4.isFile());         System.out.println(file4.exists());         System.out.println(file4.canRead());         System.out.println(file4.canWrite());         System.out.println(file4.isHidden());     } 复制代码

输出结果:

如何快速了解Java中的IO流

如何快速了解Java中的IO流

2.2.3 File类的其他功能
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false。指定文件的目录要存在。 public boolean delete():删除文件或者文件夹,删除注意事项:Java中的删除不走回收站。要想文件夹删除成功,最后一个文件目录下不能有子目录或文件

  @Test     public void test6() throws IOException {         File file1 = new File("hello.txt");//此时文件不存在         if (!file1.exists()){             //文件的创建             boolean newFile = file1.createNewFile();             System.out.println("文件创建成功");         }else{             boolean delete = file1.delete();             System.out.println("原文件删除成功");         }     } 复制代码

如何快速了解Java中的IO流

如何快速了解Java中的IO流

public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建

@Test public void test7() {     //文件目录的创建     File file1 = new File("d:\\io\\io1\\io2");//此时只有io目录存在     boolean mkdir = file1.mkdir();     if (mkdir) {         System.out.println("创建成功1");     }      File file2 = new File("d:\\io\\io1\\io2");//此时只有io目录存在     boolean mkdirs = file2.mkdirs();     if (mkdirs) {         System.out.println("创建成功2");     } } 复制代码

输出结果:

如何快速了解Java中的IO流

public boolean renameTo(File dest):把文件重命名为指定的文件路径,比如:file1.renameTo(file2)为例: 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。

@Test   public void test9(){       File file1 = new File("hello.txt");//在硬盘中存在内容为"hello world!"       File file2 = new File("D:\\io\\hi.txt");//hi.txt不存在       boolean renameTo = file1.renameTo(file2);       System.out.println(renameTo);   } 代码

输出结果:生成了原本不存在的hi.txt文件,内容为hello world! hello.txt位置发生移动。

如何快速了解Java中的IO流

idea中main()方法中File的默认相对路径和Junit Test 方法中File的路径不同

public class FileMainTest {     public static void main(String[] args) {         File file = new File("hello.txt");         System.out.println("main" + file.getAbsoluteFile());//输出结果:mainD:\JavaSE\JavaProject\WorkSpace\hello.txt     }      @Test     public void test1() {         File file = new File("hello.txt");         System.out.println("test" + file.getAbsoluteFile());//输出结果:testD:\JavaSE\JavaProject\WorkSpace\ioDemo\hello.txt     } } 复制代码

二. IO流
1. 简单介绍
Java 提供了许多实现文件输人 / 输出的类。这些类可以分为文本 I/O 类(text I/O class)和二进制 I/O 类(binary I/O class)。

输入对象(输入流)读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中,操作过程中,我们是以 程序(内存)的角度。
输出对象(输出流)将程序(内存)数据输出到磁盘、光盘等存储设备中。

如何快速了解Java中的IO流

1.1 流的分类

Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个 抽象基类派生的。 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

如何快速了解Java中的IO流

2. 节点流(文件流)

2.1 FileReader/FileWriter(字符流)
2.1.1 FileReader常用方法

2.1.2 基本用法
几乎所有的I/O类中的方法都会抛出异常 ;java.io.IOException。因此,必须在方法中声明会抛出:java.io.IOException 异常,或者将代码放到 try-catch 块中。

//将module下的hello.txt文件内容读入程序中,并输出到控制台  @Test     public void test1() throws IOException {         FileReader fr = null;         try {             //1.File类的实例化             File file = new File("hello.txt");                          //2.FileReader流的实例化             fr = new FileReader(file);                          //3.读入的操作 使用read(char[] cbuf)             char[] cbuf = new char[5];             int len;             while ((len = fr.read(cbuf)) != -1) {                 //方法一                 // for (int i = 0; i < len; i++) {//不能用cbuf.length                 //     System.out.print(cbuf[i]);                 // }                 //方法二                 String s = new String(cbuf, 0, len);                 System.out.print(s);             }         } catch (IOException e) {             e.printStackTrace();         } finally {             if (fr != null) {                 try {                     //4.资源的关闭                     fr.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }         }     } 复制代码

输出结果:

如何快速了解Java中的IO流

2.1.1 FileWriter常用方法

2.1.2 基本用法

  1. 鸿蒙官方战略合作共建——HarmonyOS技术社区

  2. 输出操作,对应的File可以不存在的。并不会报异常

  3. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。 File对应的硬盘中的文件如果存在: ① 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖 ② 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容

//从内存中写出数据到硬盘的文件里 @Test     public void test2() {         FileWriter fw = null;         try {             //1.创建File类的对象,指明写出的文件             File file = new File("hello1.txt");              //2.提供FileWrite的对象,用于数据的写出             fw = new FileWriter(file);              //3.写出的操作             fw.write("I have a dream!\n");             fw.write("you need to have a dream!");         } catch (IOException e) {             e.printStackTrace();         } finally {             if (fw != null) {                 //4.关闭资源                 try {                     fw.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }         }     } 复制代码

如何快速了解Java中的IO流

实现文本之间的复制

@Test    public void test3() {        FileReader fr = null;        FileWriter fw = null;        try {            //1.创建File类的对象,指明读入与写出的文件            File srcFile = new File("hello.txt");            File destFile = new File("hello2.txt");             //2.創建输入流与输出流的对象            fr = new FileReader(srcFile);            fw = new FileWriter(destFile);             //3.数据的读入与写出的操作            char[] cbuf = new char[5];            int len;            while ((len = fr.read(cbuf)) != -1) {                fw.write(cbuf, 0, len);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            //4.关闭流资源            try {                if (fw != null)                    fw.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                if (fr != null)                    fr.close();            } catch (IOException e) {                e.printStackTrace();            }        }    } 制代码

2.2 FileInputStream/FileOutputStream(字节流)
2.2.1 FileInputStream常用方法

2.2.2 FileOutputStream常用方法

2.2.3 基本用法

@Test    public void test1() {        FileInputStream fis = null;        FileOutputStream fos = null;        try {            //1.造文件对象            File srcFile = new File("photo1.jpg");            File destFile = new File("photo2.jpg");             //2.造流            fis = new FileInputStream(srcFile);            fos = new FileOutputStream(destFile);             //3.读数据            byte[] buffer = new byte[5];            int len;            while ((len = fis.read(buffer)) != -1) {                fos.write(buffer, 0, len);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            //4.关闭资源            try {                if (fos != null)                    fos.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                if (fis != null)                    fis.close();            } catch (IOException e) {                e.printStackTrace();            }        }    } 制代码

复制成功

如何快速了解Java中的IO流

3.缓冲流

3.1 BufferedInputStream/BufferedOutputStream

  @Test     public void test1() {         BufferedInputStream bis = null;         BufferedOutputStream bos = null;         try {             //1.造文件对象             File srcFile = new File("D:\\QQmusic\\MV\\1988.mp4");             File descFile = new File("D:\\QQmusic\\MV\\copy1988.mp4");              //2.1造节点流             FileInputStream fis = new FileInputStream(srcFile);             FileOutputStream fos = new FileOutputStream(descFile);              //2.2造缓冲流             bis = new BufferedInputStream(fis);             bos = new BufferedOutputStream(fos);              //3.数据读入与写出操作             byte[] buffer = new byte[1024];             int len;             while ((len = bis.read(buffer)) != -1) {                 bos.write(buffer, 0, len);             }         } catch (IOException e) {             e.printStackTrace();         } finally {             //4.关闭资源             try {                 if (bos != null)                     bos.close();             } catch (IOException e) {                 e.printStackTrace();             }             try {                 if (bis != null)                     bis.close();             } catch (IOException e) {                 e.printStackTrace();             }             //说明:先关闭外层的流,再关闭内层的流             // 关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略. //        fos.close(); //        fis.close();         }     } 复制代码

结果:成功复制

如何快速了解Java中的IO流

3.2 BufferedReader/BufferedWriter

 @Test     public void test2() throws IOException {         BufferedReader br = null;         BufferedWriter bw = null;         try {             //创建文件和相应的流             //  BufferedReader br = new BufferedReader(new FileReader(new File("hello.txt")));             br = new BufferedReader(new FileReader("hello.txt"));             bw = new BufferedWriter(new FileWriter("hello3.txt"));              //读写操作             //方式一             char[] cbuf = new char[1024];             int len;             while ((len = br.read(cbuf)) != -1) {                 bw.write(cbuf, 0, len);             } //        //方式二 //        String data; //        while ((data = br.readLine())!= null){//一次读取字符文本文件的一行字符 //            bw.write(data);//data中不包含换行符, 一次写入一行字符串 //            bw.newLine(); //            //bw.write(data + "\n"); //        }         } catch (IOException e) {             e.printStackTrace();         } finally {             try {                 if (bw != null)                     bw.close();             } catch (IOException e) {                 e.printStackTrace();             }             try {                 if (br != null)                     br.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     } 复制代码

4.转换流
4.1 InputStreamReader/OutputStreamWriter

 /**      * 综合使用InputStreamReader和OutputStreamWriter      */     @Test     public void test1() {         InputStreamReader isr = null;//默认IDE的字符集         OutputStreamWriter osw = null;         try {             //1.造文件对象             File file1 = new File("hello.txt");             File file2 = new File("hello_gbk.txt");             //2.造流             FileInputStream fis = new FileInputStream(file1);             FileOutputStream fos = new FileOutputStream(file2);              //InputStreamReader isr = new InputStreamReader(fis,"UTF-8");             isr = new InputStreamReader(fis);              osw = new OutputStreamWriter(fos, "gbk");             //OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");              //3.数据读写过程             char[] cbuf = new char[20];             int len;             while ((len = isr.read(cbuf)) != -1) {                 osw.write(cbuf, 0, len);             }         } catch (IOException e) {             e.printStackTrace();         } finally {             //4.关闭资源             try {                 if (isr != null)                     isr.close();             } catch (IOException e) {                 e.printStackTrace();             }             try {                 if (osw != null)                     osw.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     } 复制代码

如何快速了解Java中的IO流

如何快速了解Java中的IO流

5.对象流
5.2 对象的的序列化

谈谈你对java.io.Serializable接口的理解,我们知道它用于序列化,是空方法接口,还有其它认识吗?

实现了Serializable接口的对象,可将它们转换成一系列字节,并可在以后完全恢复回原来的样子。这一过程亦可通过网络进行。这意味着序列化机制能自动补偿操作系统间的差异。换句话说,可以先在Windows机器上创建一个对象,对其序列化,然后通过网络发给一台Unix机器,然后在那里准确无误地重新“装配”。不必关心数据在不同机器上如何表示,也不必关心字节的顺序或者其他任何细节。 由于大部分作为参数的类如String、Integer等都实现了java.io.Serializable的接口,也可以利用多态的性质,作为参数使接口更灵活。

5.1 ObjectInputStream/ObjectOutputStream
若某个类实现了 Serializable 接口,该类的对象就是可序列化的:

  1. 鸿蒙官方战略合作共建——HarmonyOS技术社区

  2. 创建一个 ObjectOutputStream

  3. 调用 ObjectOutputStream 对象的writeObject(对象) 方法输出可序列化对象

  4. 注意写出一次,操作flush()一次

反序列化

  1. 鸿蒙官方战略合作共建——HarmonyOS技术社区

  2. 创建一个 ObjectInputStream

  3. 调用 readObject() 方法读取流中的对象

强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化

package objectTest;  import org.junit.Test;  import java.io.*;  /**  * @author mazouri  * @create 2020-04-21 20:08  */ public class ObjectInOutputStream {     /**      * 序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去      * 使用ObjectOutputStream实现      */     @Test     public void test1() {         ObjectOutputStream oos = null;         try {             oos = new ObjectOutputStream(new FileOutputStream("object.dat"));             oos.writeObject(new Person("张三", 18));             //刷新操作             oos.flush();              oos.writeObject(new Person("李四", 23, 1001, new Account(5000)));             oos.flush();         } catch (IOException e) {             e.printStackTrace();         } finally {             try {                 if (oos != null)                     oos.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     }      /*      *反序列化:将磁盘文件中的对象还原为内存中的一个java对象      *使用ObjectInputStream来实现      */     @Test     public void test2() {         ObjectInputStream ois = null;         try {             ois = new ObjectInputStream(new FileInputStream("object.dat"));              Person p = (Person) ois.readObject();             Person p1 = (Person) ois.readObject();              System.out.println(p + "\n" + p1);         } catch (IOException | ClassNotFoundException e) {             e.printStackTrace();         } finally {             try {                 if (ois != null)                     ois.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     } } 复制代码

输出结果:

如何快速了解Java中的IO流

6.随机存取文件流

6.1 RandomAccessFile
构造器

  @Test     public void test1() {          RandomAccessFile raf1 = null;         RandomAccessFile raf2 = null;         try {             //1.             raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");             raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");             //2.             byte[] buffer = new byte[1024];             int len;             while((len = raf1.read(buffer)) != -1){                 raf2.write(buffer,0,len);             }         } catch (IOException e) {             e.printStackTrace();         } finally {             //3.             if(raf1 != null){                 try {                     raf1.close();                 } catch (IOException e) {                     e.printStackTrace();                 }              }             if(raf2 != null){                 try {                     raf2.close();                 } catch (IOException e) {                     e.printStackTrace();                 }              }         }     }      @Test     public void test2() throws IOException {          RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");          raf1.seek(3);//将指针调到角标为3的位置         raf1.write("xyz".getBytes());//          raf1.close();      }     /*     使用RandomAccessFile实现数据的插入效果      */     @Test     public void test3() throws IOException {          RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");          raf1.seek(3);//将指针调到角标为3的位置         //保存指针3后面的所有数据到StringBuilder中         StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());         byte[] buffer = new byte[20];         int len;         while((len = raf1.read(buffer)) != -1){             builder.append(new String(buffer,0,len)) ;         }         //调回指针,写入“xyz”         raf1.seek(3);         raf1.write("xyz".getBytes());          //将StringBuilder中的数据写入到文件中         raf1.write(builder.toString().getBytes());          raf1.close();     } }

到此,关于“如何快速了解Java中的IO流”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. java中的IO流
  2. java中的io流是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何用Python爬取英雄联盟(lol)全部皮肤

下一篇:python如何爬取基金股票最新数据并用excel绘制树状图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》