JavaSE -- IO流

file类

绝对路径:是一个固定的路径,从盘符开始
相对路径:是相对于某个位置开始
路径分隔符:
windows:\
unix:/

     import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
 * 2. File类声明在java.io包下
 * 3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,
 *    并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
 *
 *
 *
 *
 *
 * @author lenovo
 */
public class FileTest {
    @Test
    public void test01() {
/**public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果
 pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
 绝对路径:是一个固定的路径,从盘符开始
 相对路径:是相对于某个位置开始,从你写代码的上一层路径开始算
 public File(String parent,String child)
 以parent为父路径,child为子路径创建File对象。  public File(File parent,String child)
 根据一个父File对象和子文件路径创建File对象
 */
//这里只是构造器 并没有真实创建文件
        File file1 = new File("io.txt");
        File file2 = new File("E:\\openidea\\iotest\\src\\io.txt");
        System.out.println(file1);
        System.out.println(file2);
        File file3 = new File("E:\\openidea", "iotest");
        System.out.println(file3);
        File file4 = new File(file3, "hi.txt");
        System.out.println(file4);

    }

    @Test
    public void Test02() {
//        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数组
        File file1 = new File("io.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(new Date(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());

    }

    @Test
    public void Test03() {
        File file = new File("E:\\openidea");
        //相对路径
        String[] list = file.list();
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println();
        //绝对路径
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(f);
        }

    }

    @Test
    public void Test04() {
        //public boolean renameTo(File dest):把文件重命名为指定的文件路径
        // 要想保证返回true,需要 被改名文件 在硬盘中是存在的,且 改名 的不能在硬盘中存在。
        File file2 = new File("d:\\hi.txt");
        File file1 = new File("E:\\openidea\\hello.txt");
        boolean renameTo = file2.renameTo(file1);
        System.out.println(renameTo);
    }

    @Test
    public void Test05() {
//         public boolean isDirectory():判断是否是文件目录
//         public boolean isFile() :判断是否是文件
//         public boolean exists() :判断是否存在
//         public boolean canRead() :判断是否可读
//         public boolean canWrite() :判断是否可写
//         public boolean isHidden() :判断是否隐藏
        File file1 = new File("E:\\openidea\\hello.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());
    }

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

        }
    }
}

I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

节点流
直接从数据源或目的地读写数据。
处理流
不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。

字符流(文件流)

main方法和Test区别:
main相较于当前工程
Test相较于当前Module
不能处理非文本文件
FileReader
FileWriter

import org.junit.Test;

import java.awt.color.ICC_Profile;
import java.io.*;

/**
 * @author lenovo
 */
public class FileReaderWriterTest {
    //1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
//2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
//3. 读入的文件一定要存在,否则就会报FileNotFoundException。
    @Test
    //FileReader
    public void test01() throws Exception {
        //FileReader fr =null;
        //1.实例化File类的对象,指明要操作的文件
        File file = new File("iotest.txt");
        //等同于
        FileReader fr = new FileReader("iotest.txt");
        //2.提供具体的流,提供文件的流
        fr = new FileReader(file);
        //3读取
        // System.out.println((char) fr.read());//只读取一个
        int data;
        while ((data = fr.read()) != -1) { //读取不到返回-1
            System.out.print((char) data);
        }
        //4关闭
        fr.close();
    }

    @Test
    public void test02() throws Exception {
        FileReader fr = null;
        //1.实例化File类的对象,指明要操作的文件
        File file = new File("iotest.txt");
        //2.提供具体的流,提供文件的流
        fr = new FileReader(file);
        //3读取
        //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
        //读取的字符放入c中
        char[] c = new char[3];
        int len;
        while ((len = fr.read(c)) != -1) {
            for (int i = 0; i < len; i++) {   //注意这里使用是len
                System.out.print(c[i]);
            }
        }
        //4关闭
        fr.close();
    }

    @Test
//    从内存中写出数据到硬盘的文件里。
//    1. 输出操作,对应的File可以不存在的。并不会报异常
//    2.
//    File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
//    File对应的硬盘中的文件如果存在:
//    如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
//    如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容

    public void testFileWriter() throws IOException {
        FileWriter fw = null;
        //1.提供File类的对象,指明写出到的文件
        File file = new File("iotest1.txt");
        //2.提供FileWriter的对象,用于数据的写出
        fw = new FileWriter(file, false); //对原文件进行覆盖
        //3.写出的操作
        fw.write("I have a dream!\n");
        fw.write("you need to have a dream!");
        //4.流资源的关闭
        fw.close();
    }
    @Test
    //同时写和读
    public void test03() throws Exception {
        FileWriter fw = null;
        FileReader fr = null;
        //1.创建File类的对象,指明读入和写出的文件
        //不能使用字符流来处理图片等字节数据
        File srcFile = new File("iotest1.txt");
        File destFile = new File("iotest3.txt");
        //2.创建输入流和输出流的对象
        fr = new FileReader(srcFile);
        fw = new FileWriter(destFile);
        //数据的读入和写出操作
        char[] c =new char[5];
        int len;
        while ((len=fr.read(c))!=-1){
            fw.write(c,0,len);
        }
        //关闭
        fr.close();
        fw.close();
    }
}

字节流(非文本文件)

对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
FileInputStream意思指对文件数据以字节的形式进行读取操作如读取图片视频等
FileOutputStream写入数据到File对象表示的文件

import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author lenovo
 */
public class FileInputOutputStreamTest {
    //指定路径下文件的复制
    public void copyFile(String srcPath,String destPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);

            //
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                //
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }
    @Test
    public void testCopyFile(){

        long start = System.currentTimeMillis();

        String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi";
        String destPath = "C:\\Users\\Administrator\\Desktop\\02-视频.avi";


//        String srcPath = "hello.txt";
//        String destPath = "hello3.txt";

        copyFile(srcPath,destPath);


        long end = System.currentTimeMillis();

        System.out.println("复制操作花费的时间为:" + (end - start));//618

    }
}

缓冲流(处理流)

处理非文本数据
BufferedInputStream
BufferedOutputStream
处理文本数据
BufferedReader
BufferedWriter
不能直接作用到文件上
代码层面

造节点流
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

关闭流的时候,先关外面,后关里面

//关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
bos.close();
bis.close();
fos.close();
bos.close();

当对比时

long end = System.currentTimeMillis();
ong start = System.currentTimeMillis();

byte[] buffer = new byte[1024];
相同时,缓冲流时间比较快

提供流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区

public BufferedInputStream(InputStream in) {
        this(in, DEFAULT_BUFFER_SIZE);
private static int DEFAULT_BUFFER_SIZE = 8192;
 flush()方法的使用:刷新缓冲区

 //实现文件复制的方法
    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
            //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.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
//        fos.close();
//        fis.close();
        }
    }
    

转换流

InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
解码:字节、字节数组 —>字符数组、字符串
编码:字符数组、字符串 —> 字节、字节数组

FileInputStream fis = new FileInputStream("dbcp.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
        //参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用系统默认的字符集

对象流(序列化,反序列化)

序列化
用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化
用ObjectInputStream类读取基本类型数据或对象的机制

ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

Java对象的序列化
是将内存中的java对象转化为二进制的字节流,然后保存到磁盘中或者在网络上。这就是序列化对象,反序列化顾名思义就是将对象的二进制字节流恢复成原来的对象。注意只有对象的类名和属性能被序列化(包括基本类型,数组,对其他对象的引用)不包括方法,static属性(静态属性)transient属性(瞬态属性)都不会被序列化。

如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现SerializableExternalizable两个接口之一。否则,会抛出NotSerializableException异常

对象序列化

import com.sun.corba.se.impl.io.OutputStreamHook;
import org.junit.Test;

import java.io.*;

/**
 * @author lenovo
 */
public class ObjectInputOutputStreamTest {
    @Test
    public void test01(){
        //序列化,写入到内存层面,防止被删除
        ObjectOutputStream oos =null;
        try {
            //1.造对象
             oos =new ObjectOutputStream(new FileOutputStream("Object.txt"));
            //2.造流, 存储和读取基本数据类型数据或对象的处理流 ,这里为对象
            oos.writeObject(new String("小猫咪喵喵喵"));
            //3.注意写出一次,操作flush()一次 ,刷新操作
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (oos !=null)
        //4.关闭
        {
            try {
                oos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    @Test
    public void test02(){
        //反序列化
        ObjectInputStream ois = null;
        try {
            InputStream in;
            //1.造对象
            ois = new ObjectInputStream(new FileInputStream("Object.txt"));
            //2.造流
            Object o = ois.readObject();
            String str = (String) o;
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }if(ois !=null)
        //3.关闭,没有刷新
        {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

自定义序列化
自定义的类不是可序列化的java.io.NotSerializableException: Person
可序列化继承 Serializable接口,Externalizable
其接口是空的,这是一种标识化接口
public interface Serializable {
}
需要补充一个序列版本号,自定义异常类都需要补充一个序列版本号
public static final long serialVersionUID = 4754456674532L;

import java.io.Serializable;

/**
 *
 * /**
 *  * Person需要满足如下的要求,方可序列化
 *  * 1.需要实现接口:Serializable
 *  * 2.当前类提供一个全局常量:serialVersionUID,序列版本号
 *  * 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
 *  *   也必须是可序列化的。(默认情况下,基本数据类型可序列化)
 *  *
 *  *
 *  * 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
 *  *
 *  *
 * @author lenovo
 */
public class Person implements Serializable {
    //serialVersionUID,序列版本号
    public static final long serialVersionUID = 4754456674532L;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

}


import org.junit.Test;

import java.io.*;

/**
 * @author lenovo
 */
public class PersonTest {
    @Test
    public void test01(){
        //序列化,写入到内存层面,防止被删除
        ObjectOutputStream oos =null;
        try {
            //1.造对象
            oos =new ObjectOutputStream(new FileOutputStream("Object1.txt"));
            //2.造流, 存储和读取基本数据类型数据或对象的处理流 ,这里为对象
           // oos.writeObject(new String("小猫咪喵喵喵"));
            oos.writeObject(new Person("小猫",23));
            //3.注意写出一次,操作flush()一次 ,刷新操作
           // oos.flush();
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (oos !=null)
        //4.关闭
        {
            try {
                oos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    @Test
    public void test02(){
        //反序列化
        ObjectInputStream ois = null;
        try {
            InputStream in;
            //1.造对象
            ois = new ObjectInputStream(new FileInputStream("Object1.txt"));
            //2.造流
            Person o =(Person)ois.readObject();//强制转换为Person
            System.out.println(o);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }if(ois !=null)
        //3.关闭,没有刷新
        {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}



serialVersionUID

private static final long serialVersionUID;
private static final long serialVersionUID = xxx;
serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议,显式声明。

简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验
证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同
就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异
常。(InvalidCastException)
当对内容进行修改时,系统会为它自动分配一个序列化值,当进行反序列化时就会出错,就是系统找不到当时的那个类了。

随机存取文件流(RandomAccessFile 类)

如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。
我们可以用RandomAccessFile这个类,来实现一个多线程断点下载的功能,用过下载工具的朋友们都知道,下载前都会建立两个临时文件,一个是与被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次暂停的时候,都会保存上一次的指针,然后断点下载的时候,会继续从上一次的``地方下载,从而实现断点下载或上传的功能。

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author lenovo
 *
 * r: 以只读方式打开
 * rw:打开以便读取和写入
 * rwd:打开以便读取和写入;同步文件内容的更新
 * rws:打开以便读取和写入;同步文件内容和元数据的更新
 * 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
 * 如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
 */
public class RandomAccessFileTest {
           @Test
            public void tesst01(){
               RandomAccessFile raf = null;
               try {
                   raf = new RandomAccessFile(new File("iotest.txt"), "r");
                  byte[] b =new byte[1024];

                   raf.seek(0);
//                   int len;
//                   while((len = raf.read(b))!=-1){
//                       for (int i = 0; i <len ; i++) {
//                           System.out.print((char)b[i]);
//                       }
//                   }
                 String s = raf.readLine();
                   System.out.println(s);//IO流hel123orld123
                   //转换字
     //使用 RandomAccessFile对象方法的 readLine() 都会将编码格式转换成 ISO-8859-1 所以输出显示是还要在进行一次转码。
                   s =new String(s.getBytes("ISO-8859-1"));
                   System.out.println(s);//IO流hel123orld123
               } catch (IOException e) {
                   e.printStackTrace();
               }if(raf!=null) {
                   try {
                       raf.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }

           }

    @Test
    public void tesst02() throws Exception{

            RandomAccessFile raf = null;

                raf = new RandomAccessFile(new File("iotest.txt"), "rw");
                raf.seek(3);//调整角标
        // public void seek(long pos) throws IOException {
        //        if (pos < 0) {
        //            throw new IOException("Negative seek offset");
        //        } else {
        //            seek0(pos);
        //        }
        //    }
                raf.write("123".getBytes());//写入数据,有数据进行覆盖,没有就写
                raf.close();
                //public void write(byte b[]) throws IOException {
        //        writeBytes(b, 0, b.length);
        //    }
        /*
    使用RandomAccessFile实现数据的插入效果
     */}
        @Test
        public void test3() throws IOException {

            RandomAccessFile raf1 = new RandomAccessFile("iotest.txt","rw");

            raf1.seek(3);//将指针调到角标为3的位置
            //保存指针3后面的所有数据到StringBuilder中
            StringBuilder builder = new StringBuilder((int) new File("iotest.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();

            //思考:将StringBuilder替换为ByteArrayOutputStream
        }



}



添加jar包

复制好包,在目录下新建lib的一个Directory,添加进去,点击右键,选择Add as Library,点击ok ,此时作为一个api可以使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值