io_Nio_netty

IO流

io_Nio_netty

 二:File类

java.io.File类:文件和目录路径名的抽象表示形式,与平台无关。File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。File对象可以作为参数传递给流的构造函数。

File类的常见构造方法:
public File(String pathname)
以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储(可以通过system.getproperty("user.dir")查看)
public File(String parent,String child)
以parent为父路径,child为子路径创建File对象

io_Nio_netty

字符流以字符为单位,字节流以byte为单位

 io_Nio_netty

 io_Nio_netty

 io_Nio_netty

 因此BufferedReader和BufferedWriter可以包装在FileReader和FileWriter上加快文件读写速度。

io_Nio_netty

 3.1 输入输出流的基类InputStream和Reader,OutputStram和Writer

io_Nio_netty

 io_Nio_netty

io_Nio_netty
package IO;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestInputOutput {
    @Test
    public void test1() {//读取文件,并把结果输出到控制台上面
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File("src/IO/config.txt"));
            byte[] b = new byte[5];
            int len;
            while ((len = fis.read(b)) != -1) {
                System.out.print(new String(b, 0, len));
            }

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

    @Test
    public void test2() {
        // 1.创建一个File对象,表明要写入的文件位置。
        // 输出的物理文件可以不存在,当执行过程中,若不存在,会自动的创建。若存在,会将原有的文件覆盖
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(new File("src/IO/b.txt"));
            fos.write("你好,我在发消息".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void test3(){// 从硬盘读取一个文件,并写入到另一个位置。(相当于文件的复制)
        FileInputStream fis = null;
        FileOutputStream fos = null;
        long start = System.currentTimeMillis();
        try {
            fis = new FileInputStream(new File("a.jpg"));
            fos = new FileOutputStream(new File("a1.jpg"));
            byte[] b = new byte[1000];//会发现数组的大小影响文件写出的效率,文件太小多次写入浪费时间,太大则浪费空间。
            int len;
            while ((len = fis.read(b))!=-1){
                fos.write(b,0,len);//注意使用len而不是b.length的原因是防止在后一次循环若数组为读满导致多余的数据被写入的错误
            }

        } 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();
                }
            }

        }
        long end = System.currentTimeMillis();
        System.out.println("时间共花了"+(end-start));
    }
}
View Code

io_Nio_netty

3.5转换流

io_Nio_netty

 io_Nio_netty

io_Nio_netty

 io_Nio_netty

3.7 打印流

 io_Nio_netty

io_Nio_netty
  @Test
    public void test3() throws IOException {
        FileOutputStream fos = new FileOutputStream(new File("b.txt"));
        PrintStream printStream = new PrintStream(fos);
        if(printStream != null){
            System.setOut(printStream);//改变流的方向
        }
        System.out.println("这句话将输入到b.txt文件而不是控制台");
        printStream.close();
        InputStream inputStream = new FileInputStream("b.txt");
        System.setIn(inputStream);//输入被调整为从文件里面输入
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }
        inputStream.close();
    }
io_Nio_netty

3.8数据流

 io_Nio_netty

io_Nio_netty
   @Test
    public void test4() throws Exception {//数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStream DataOutputStream
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("data.txt"));
        dataOutputStream.writeUTF("我爱你,而你不知道");
        dataOutputStream.writeBoolean(true);
        dataOutputStream.writeInt(12);
        dataOutputStream.close();//会乱码,但是再次读的时候会恢复
        DataInputStream dataInputStream = new DataInputStream(new FileInputStream(new File("data.txt")));
//        byte[] b =new byte[10];
//        int len;
//        while((len = dataInputStream.read(b))!=-1){
//            System.out.println(new String(b,0,len));
//        }
        System.out.println(dataInputStream.readUTF());
        System.out.println(dataInputStream.readBoolean());
        System.out.println(dataInputStream.readInt());
        dataInputStream.close();
    }
io_Nio_netty

3.9对象流

io_Nio_netty

 io_Nio_netty

 io_Nio_netty

 io_Nio_netty

io_Nio_netty io_Nio_netty
package IO;

import org.junit.Test;

import java.io.*;

public class TestObjectInputOutputStream {
    @Test
    public void test() throws IOException {// 对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中
        Person person = new Person("花花", 12, new Pet("哈哈"));
        Person person1 = new Person("瓜瓜", 22, new Pet("大大"));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt"));
        oos.writeObject(person);
        oos.flush();
        oos.writeObject(person1);
        oos.flush();
        oos.close();
    }
    @Test
    public void test1() throws IOException, ClassNotFoundException {// // 对象的反序列化过程:将硬盘中的文件通过ObjectInputStream转换为相应的对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"));
        Person person = (Person) ois.readObject();
        Person person1 = (Person) ois.readObject();
        System.out.println(person);
        System.out.println(person1);
    }
}
/*
 * 要实现序列化的类: 1.要求此类是可序列化的:实现Serializable接口
 * 2.要求类的属性同样的要实现Serializable接口
 * 3.提供一个版本号:private static final long serialVersionUID
 * 4.使用static或transient修饰的属性,不可实现序列化
 */
class Person implements Serializable{
    private static final long serialVersionUID = 23456789L;
    String name;
    Integer age;
    Pet pet;
    public Person(String name, Integer age,Pet pet) {
        this.name = name;
        this.age = age;
        this.pet = pet;
    }

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

    public Pet(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                '}';
    }
}
View Code
io_Nio_netty

  transient是 Java语言的关键字,变量修饰符,如果用transient声明一个实例变量,当对象存储时,它的值不需要维持。换句话来说就是,用transient关键字标记的成员变量不参与序列化过程

3.10 randomAccessFile类

io_Nio_netty

 io_Nio_netty

io_Nio_netty
package IO;

import org.junit.Test;

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

public class TestRandomAccessFile {
    @Test//RandomAccessFile进行文件的读写
    public void test1() throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile(new File("src/IO/a.txt"),"r");
        RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("src/IO/aa.txt"),"rw");
        int len;
        byte[] b = new byte[10];
        while ((len = randomAccessFile.read(b))!=-1){
            randomAccessFile1.write(b,0,len);
        }
        randomAccessFile1.close();
        randomAccessFile.close();
    }
    @Test//实现的实际上是覆盖的效果
    public void test2() throws Exception {
        RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("src/IO/aa.txt"),"rw");
        randomAccessFile1.seek(4);
        randomAccessFile1.write("xy".getBytes());//在第四个字符出写入xy,实则是覆盖,注意汉字一个字占两个字符,如26个字符覆盖后abcdxyghijklmnopqrstuvwxyz
        randomAccessFile1.close();
    }
    @Test//处理覆盖
    public void test3() throws Exception {
        RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("src/IO/aa.txt"),"rw");
        randomAccessFile1.seek(4);
        String str = randomAccessFile1.readLine();//弊端是只能处理一行
        randomAccessFile1.seek(4);//指针已经移动,需要调整
        randomAccessFile1.write("xy".getBytes());
        randomAccessFile1.write(str.getBytes());//拿出来在追加上
        randomAccessFile1.close();//abcdxyefghijklmnopqrstuvwxyz
    }
    @Test//更通用
    public void test4() throws Exception {
        RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("src/IO/aa.txt"),"rw");
        randomAccessFile1.seek(4);
        byte[] b = new byte[10];
        int len;
        StringBuffer sb = new StringBuffer();
        while((len = randomAccessFile1.read(b)) != -1){
            sb.append(new String(b,0,len));
        }
        randomAccessFile1.seek(4);//指针已经移动,需要调整
        randomAccessFile1.write("xy".getBytes());
        randomAccessFile1.write(sb.toString().getBytes());//拿出来在追加上
        randomAccessFile1.close();//abcdxyefghijklmnopqrstuvwxyz
    }

}
View Code

BIO-NIO-AIO

-=io_Nio_netty

 

上一篇:netty系列之:自定义编码解码器


下一篇:RESTful风格简化路由文件