轻松入门编程,月入过万不是梦(Java中的IO流)

Java中的IO流

File类的使用

  • java.io.File类:文件和文件目录路径的抽象表现形式,与平台无关
  • File能新建、删除、重命名文件和目录,但File不能访问文件内容本身,如果需要访问文件内容本身,则需要使用输入/输出流
  • 想要在Java程序中表示一个真实存在的文件或,目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
  • File对象可以作为参数传递给流的构造器
 /*1、如何创建一个File类的实例
 *       File file = new File(String filePath)
 *       File file = new File(String parentPath,String childPath)
 *       File file = new File(File parentFile,String childPath)
 * 2、相对路径:相较于某个路径下,指明的路径
 *   绝对路径:包含盘符在内的文件或文件目录的路径
 *
 * 3、路径分隔符
 * windows:\
 * unix:/
 * */

File类的获取功能

 public String getAbsolutePath():获取绝对路径
 public String getPath():获取路径
 public String getName():获取名称
 public String getParent():获取上层文件目录路径。若无,返回null
 public long length():获取文件长度(即:字节数)。不能获取目录的长度
 public long lastModified():获取最后一次修改时间,毫秒值
 //适用于文件目录
 public String[] list():获取指定目录下的所有文件或者文件目录的名称数组
 public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组
 
 //测试
  @Test
     public void test1(){
         //构造器1:
         File file = new File("hello.txt");//相对于当前module
         System.out.println(file.getAbsolutePath());
         System.out.println(file.getPath());
         System.out.println(file.getName());
         System.out.println(file.getParent());
         System.out.println(file.length());
         System.out.println(new Date(file.lastModified()));
 
     }

File类的重命名功能

 public boolean renameTo(File dest):把文件重命名为指定的文件路径
 要想保证成功,必须保证调用方法的文件时不存在的,dest是不存在的

File类的判断功能

 public boolean isDirectory():判断是否是文件目录
 public boolean isFile():判断是否是文件
 public boolean exists():判断是否存在
 public boolean canReady():判断是否可读
 public boolean canWrite():判断是否可写
 public boolean isHidden():判断是否隐藏
 
 //测试
  @Test
     public void test2(){
         //构造器1:
         File file = new File("hello.txt");//相对于当前module
         System.out.println(file.isDirectory());
         System.out.println(file.isFile());
         System.out.println(file.exists());
         System.out.println(file.canRead());
         System.out.println(file.canWrite());
         System.out.println(file.isHidden());
 
     }

File类的创建功能(创建硬盘中对应的文件或文件目录)

 public boolean createNewFile():创建文件,若文件存在,则不创建,返回false
 public boolean mkdir():创建文件目录。如果此文件目录存在,就不创建了,如果此文件目录的上层目录不存在,也不创建
 public boolean mkdirs():创建文件目录,如果上册文件目录不存在,一并创建
 注意事项:如果你创建文件或则文件目录没有写盘符路径,那么,默认在项目路径下。
 
 
  @Test
     public void test3() throws IOException {
         //文件的创建
         File file = new File("hi.txt");
         if(!file.exists()){
             file.createNewFile();
             System.out.println("创建成功");
         }
         else
         {
             file.delete();
             System.out.println("删除成功");
         }
 
 
     }
     @Test
     public void test4(){
         //文件目录的创建
         File file = new File("D:\ycq");
         if(file.mkdir()){
             System.out.println("创建成功");
         }
         File file1 = new File("D:\ycq\ycq");
         if(file1.mkdirs()){
             System.out.println("创建成功");
         }
 
     }

File类的删除功能

 public boolean delete():删除文件或文件夹
 删除注意事项:
 Java中的删除不走回收站。
 要删除一个文件目录,请注意该文件目录内不能包含文件或文件目录。
 

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

IO流原理及流的分类

  • 按造操作数据单位不同分为:字节流(8bit)和字符流(16bit)
  • 按照数据流的流向不同分为:输入流和输出流
  • 按照流的角色不同分为:节点流,处理流
 /*
 * 流的体系结构
 * 抽象基类          节点流                 缓冲流(处理流的一种)
 * InputStream       FileInputStream     BufferedInputStream
 * OutputStream      FileOutputStream    BufferedOutputStream
 * Reader            FileReader          BufferedReader
 * Writer            FileWriter          BufferedWriter
 *
 * */
 //测试FileReader
 说明点:
 1、read():返回读入的一个字符,如果达到文件末尾,返回-1
 2、异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
 3、读入的文件一定要存在,否则会包FileNotFoundException
 @Test
     public void testFileReader() throws IOException {
         //实例化File类的对象,指明要操作的文件
         File file = new File("hello.txt");//相较于当前Module
         //2、提供具体的流
         FileReader fr = new FileReader(file);
         //3、数据的读入
         //read():返回读入的一个字符,如果达到文件末尾,返回-1
 
         //方式一:
         /*int data = fr.read();
         while(data!=-1){
             System.out.print((char)data);
             data = fr.read();
         }*/
         //方式二:语法上针对方式一的修改
         int data;
         while((data = fr.read()) != -1){
             System.out.print((char)data);
         }
         //4、流的关闭操作
         if(fr!=null){
             fr.close();
         }
         
     }
     
     
     
      //对read()操作升级:使用read()的重载方法
     @Test
     public void testFileReader1(){
         //1、File类的实例化
         File file = new File("hello.txt");
         //2、FileReader流的实例化
         FileReader fr = null;
         try {
             fr = new FileReader(file);
             //3、读入的操作
             //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数,如果到达文件末尾,返回-1
             char[] cbuf = new char[5];
             int len;
             while((len = fr.read(cbuf)) != -1){
                 //错误的写法
                /* for (int i = 0; i < cbuf.length; i++) {
                     System.out.print(cbuf[i]);
                 }*/
                 for (int i = 0; i < len; i++) {
                     System.out.print(cbuf[i]);
                 }
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             //4、资源的关闭
             if(fr!=null){
                 try {
                     fr.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
     
     
     
      /*从内存中写出数据到硬盘的文件里
     * 说明:
     * 1、输出操作,对应的File可以不存在的,并不会报异常
     * 2、
     *   File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件
     *   File对应的硬盘中的文件如果已经存在:
     *       如果流使用的构造器是FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
     *       如果流使用的构造器是FileWriter(file,true)不会对原有文件的覆盖,而是追加内容
     * */
     @Test
     public void testFileWriter(){
         //1、提供File类的独享,指明写出到的文件
         File file = new File("hello1.txt");
         FileWriter fw = null;
         try {
             //2、提供FileWriter的对象,用于数据的写出
             fw = new FileWriter(file);
             //3、写出的操作
             fw.write("I have a dream!
");
             fw.write("You need to have a dream!");
         } catch (IOException e) {
             e.printStackTrace();
         }finally {
             if(fw!=null){
                 try {
                     fw.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
 
     }
     
     
     @Test
     public void testFileReaderFileWriter(){
         //1、创建File类的对象,指明读入和写出的文件
             File srcFile = new File("hello.txt");
             File destFile = new File("hello2.txt");
         FileReader fr = null;
         FileWriter fw = null;
         try {
             //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();
             }
         }
 
     }
 

字节流和字符流类似,把FileReader FileWriter换成FileInputStream和FileOutputStream

缓冲流的使用

 package com.haust.java;
 /*处理流之一:缓冲流的使用
 * 作用:提供流的读取、写入速度
 * 能够提高速度的原因:内部提供了一个缓存区
 * */
 
 import org.junit.Test;
 
 import java.io.*;
 
 public class BufferedTest {
     @Test
     public void BufferedStreamTest(){
         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         try {
             //1、造文件
             File src = new File("1.jpg");
             File dest = new File("2.jpg");
             FileInputStream fis = null;
             FileOutputStream fos = null;
             bis = null;
             bos = null;
             //2、造流
             fis = new FileInputStream(src);
             fos = new FileOutputStream(dest);
             //2.2 造缓冲流
             bis = new BufferedInputStream(fis);
             bos = new BufferedOutputStream(fos);
             //3、复制的细节:读取、写入
             byte[] buffer = new byte[10];
             int len;
             while((len = bis.read(buffer))!=-1){
                 bos.write(buffer,0,len);
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             //4、资源关闭
             //要求:先关闭外层的流,再关闭内层的流
             //说明:关闭外层流的同时,内层流也会自动的关闭
             if(bos!=null){
                 try {
                     bos.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
             if(bis!=null){
                 try {
                     bis.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
 
     }
 
 
 
     //实现文件复制的方法
     public void copyFileWithBuffered(String srcFile,String destFile){
         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         try {
             //1、造文件
             File src = new File(srcFile);
             File dest = new File(destFile);
             FileInputStream fis = null;
             FileOutputStream fos = null;
             bis = null;
             bos = null;
             //2、造流
             fis = new FileInputStream(src);
             fos = new FileOutputStream(dest);
             //2.2 造缓冲流
             bis = new BufferedInputStream(fis);
             bos = new BufferedOutputStream(fos);
             //3、复制的细节:读取、写入
             byte[] buffer = new byte[10];
             int len;
             while((len = bis.read(buffer))!=-1){
                 bos.write(buffer,0,len);
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             //4、资源关闭
             //要求:先关闭外层的流,再关闭内层的流
             //说明:关闭外层流的同时,内层流也会自动的关闭
             if(bos!=null){
                 try {
                     bos.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
             if(bis!=null){
                 try {
                     bis.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
 
     }
     @Test
     public void copyFileWithBufferedTest(){
         long start = System.currentTimeMillis();
         String src = "1.jpg";
         String dest = "2.jpg";
         copyFileWithBuffered(src,dest);
         long end = System.currentTimeMillis();
         System.out.println("复制操作花费的时间为:"+(end - start));
     }
 }
 

转换流

 package com.haust.java;
 /*转换流:属于字符流
 * InputStreamReader:将一个字节的输入流转换为字符的输入流
 * OutputStreamWriter:将一个字符的输出流转换为字节的输出流
 * 作用:提供字节流和字符流的转换
 *
 * 3、解码:字节、字节数组--->字符、字符串
 * */
 
 import org.junit.Test;
 
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;
 
 public class InputStreamReaderTest {
     @Test
     public void test1() throws IOException {
         FileInputStream fis = new FileInputStream("hello.txt");
 //        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
         //参数2指明了字符集,具体使用哪个字符集,取决于文件保存时的字符集
         InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
         char[] cbuf = new char[20];
         int len;
         while((len = isr.read(cbuf))!=-1){
             String str = new String(cbuf,0,len);
             System.out.println(str);
         }
         isr.close();
     }
 
 }
 
 package com.haust.java;
 /*其他流的使用
 * 1、标准的输入、输出流
 * 2、打印流
 * 3、数据流
 * */
 
 import org.junit.Test;
 
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 
 public class OtherStreamTest {
     /*1、标准的输入、输出流
     * 1.1
     * System.in:标准的输入流、默认从键盘输入
     * System.out 标准的输出流,默认从控制台输出
     * 1.2
     * System类的setIn(InputStream in)/setOut(PrintStream ps)方式下重新指定输入和输出设备
     *
     * 练习:从键盘输入字符串,要求将读取到的整行字符串能转成大写输出,然后继续输入操作
     * 直到输入e或exit时,退出程序
     *
     * 方法一:使用Scanner实现,调用next()方法,返回一个字符串
     * 方法二:使用System.in实现。
     * */
     public static void main(String[] args) {
         BufferedReader br = null;
         try {
             InputStreamReader isr = new InputStreamReader(System.in);
             br = new BufferedReader(isr);
 
             while (true){
                 System.out.println("请输入字符串:");
                 String data = br.readLine();
                 if(data.equalsIgnoreCase("e")||data.equalsIgnoreCase("exit")){
                     System.out.println("程序结束");
                     break;
                 }
                 String upperCase = data.toUpperCase();
                 System.out.println(upperCase);
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if(br!= null){
                 try {
                     br.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
 }
 
 
 
 

数据流

DataInputStream和DataOutputStream

作用:用于读取或写出基本数据类型的变量或字符串

DataInputStream中的方法

  • boolean readBoolean()
  • byye readByte()
  • char readChar()
  • float readFloat()
  • double readDouble()
  • short readShort()
  • long readLong
  • int readInt()
  • String readUTF()
  • void readFully(byte[] b)
  //将内存中的字符串、基本数据类型的变量写出到文件中
     @Test
     public void test1() throws IOException {
         DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
         dos.writeUTF("你好!");
         dos.flush();
         dos.writeInt(11);
         dos.flush();
         dos.writeBoolean(true);
         dos.flush();
         dos.close();
     }
     //将文件中存储的基本数据类型的变量和字符串读取到内存中,保存在变量中
     //注意点:读取不同类型的数据要与写入的顺序保持一致
     @Test
     public void test2() throws IOException {
         DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
 
         String s = dis.readUTF();
         int i = dis.readInt();
         boolean b = dis.readBoolean();
         System.out.println(s);
         System.out.println(i);
         System.out.println(b);
         dis.close();
     }

对象流

ObjectInputStream和ObjectOutputStream

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来

  • 序列化:用ObjectOutputStream类保存基本数据类型或对象的机制
  • 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

对象的序列化

对象的序列化机制允许吧内存中的Java对象转换成平台无关的二进制流,从而允许吧这种二进制流持久的保存在磁盘上,或通过网络这种二进制传输到另一个网络结点,当其他程序获取了这种二进制流,就可以恢复成原来的Java对象。

  /*序列化过程:将内存中的Java对象保存到磁盘中或通过网络传输出去*/
     @Test
     public void testObjectOutputStream(){
         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();
                 }
             }
         }
     }
     //反序列化:将磁盘文件中的对象还原成为内存中的一个Java对象
     @Test
     public void testObjectInputStream(){
         ObjectInputStream ois = null;
         try {
             ois = new ObjectInputStream(new FileInputStream("object.dat"));
             Object obj = ois.readObject();
 
             String str = (String) obj;
             System.out.println(str);
         } catch (IOException e) {
             e.printStackTrace();
         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         } finally {
             try {
                 if(ois!=null){
 
                     ois.close();
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
 
     }



发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章