Java IO Steam

一、File

Linux 中操作/home/fleming/project 时,

java 程序编写时要正常使用斜杠


Windows 中操作文件目录 G:\桌面源\study\src\com\google\study\throwable 时,

java 程序中应使用双反斜杠,因为第一个反斜杠会被当作转义字符

package com.google.study.file;

import org.junit.Test;

import java.io.File;
import java.sql.SQLOutput;

public class FileTest {
    @Test
    public void fileTest(){
        File dir = new File("G:\\桌面源\\study\\src\\com\\google\\study\\throwable");

        // 得到文件所处的父目录
        System.out.println(dir.getParent());
        // G:\桌面源\study\src\com\google\study

        // 查看是否为文件
        System.out.println(dir.isFile());
        // false

        // 查看文件是否存在
        System.out.println(dir.exists());
        // true

        // 获取文件大小,以字节进行计算
        System.out.println(dir.length());
        // 4096

        // 获取文件名称
        System.out.println(dir.getName());
        // throwable

        // 遍历返回文件夹下面的文件名
        String[] list = dir.list();
        for (String name:
             list) {
            System.out.println(name);
        }
        /* ErrorCode.java
           ExcepTest.java
           Exception.java
           FlemingCodeEnum.java
           FlemingException.java
           FlemingExceptionTest.java
        */

    }
}


二、I/O Stream

Stream流动
Iinput输入
Ooutput输出

I/O 流是指一个过程

I/O 流是一个相对的过程

  • input stream to read data
  • output stream to write data

请添加图片描述


三、InputStream 和 OutputStream

(字节流)

InputStream 和 OutputStream 是两个抽象类

它们有两个典型的子类 FileInputStream 和 FileOutputStream


四、FileInputStream

从 1.txt 文件中读取数据,读取出的内容为 byte 类型:

package com.google.study.io;

import com.sun.org.apache.xpath.internal.operations.String;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

public class IoTest {
    @Test
    public void inputFile() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("file/1.txt");
        int by = 0;
        while ((by = fileInputStream.read()) != -1) {
            //System.out.print(by);
            System.out.print((char)by);
        }
        System.out.println();
        fileInputStream.close();

        FileInputStream fis = new FileInputStream("file/1.txt");
        byte[] buf = new byte[3];
        int len = fis.read(buf);
        System.out.println(len + "..." + Arrays.toString(buf));
        fis.close();
    }
}
F:\DevSoftware\Java\jdk8\bin\java.exe...
1001021151001021310971001021001151021310971151001021001021310100971001310102131097100102131013109711510010213109713101151001021151310
/*
dfsdf
adfdsf
asdfdf
dad
f
adf

asdf
a
sdfs
*/
3...[100, 102, 115]

Process finished with exit code 0

五、FileOutputStream

将“fleming”字符串写入 2.txt 文件中:

 package com.google.study.io;

import com.sun.org.apache.xpath.internal.operations.String;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

public class IoTest {
    @Test
    public void outputFile() throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("file/2.txt");
        byte[] bytes = "fleming".getBytes();
        for (int i = 0; i < bytes.length; i++) {
           fileOutputStream.write(bytes[i]);
        }
        fileOutputStream.close();
    }
}

六、buff 缓冲复制文件

利用缓冲区批量读写:

public void copyFileBase() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("file/1.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("file/target.jpg");

        // 缓冲区
        byte[] buff = new byte[1024];

        int by;
        while ((by = fileInputStream.read(buff)) != -1) {
            fileOutputStream.write(buff, 0, by);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }

七、buffered 字节缓冲流和装饰设计模式

装饰设计模式,类似于提升成 vip 服务

FileInputStream 是每次单个字节的进行读入

使用 BufferedInputStream 进行提升可以一次读入多字节

@Test
public void bufferFileBase() throws IOException {
    FileInputStream fileInputStream = new FileInputStream("file/1.txt");
    BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("file/3.txt"));

    int by;
    while ((by = bufferedInputStream.read()) != -1) {
        bufferedOutputStream.write(by);
    }

    bufferedInputStream.close();
    bufferedOutputStream.close();
}

源码中限定缓冲区中一次读入了 8192 个字节:

请添加图片描述


八、FileReader 和 FileWriter

(字符流)FileReader 和 FileWriter,是用来操作 txt 文件的

FileReader 继承于 InputStreamReader

@Test
public void fileReaderTest() throws IOException {
    FileReader fileReader = new FileReader("file/1.txt");

    int ch;
    while ((ch = fileReader.read()) != -1) {
        System.out.println((char)ch);
    }
    fileReader.close();
}

FileWriter 继承于 OutputStreamReader

@Test
public void fileWriteTest() throws IOException {
    FileWriter fileWriter = new FileWriter("file/4.txt");
    fileWriter.write("Hello,FileWriter");
    fileWriter.close();
}

九、BufferedReader 和 BufferedWriter

java.io.BufferedReader 和 BufferedWriter 类各拥有 8192 字符的缓冲区,会先尽量从文件中读入字符数据并置入缓冲区。而之后若使用 read()方法,会先从缓冲区中进行读取,如果缓冲区数据不足,才会再从文件中读取:

@Test
public void bufferedWriterTest() throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("file/5.txt"));
    bufferedWriter.write("123");
    bufferedWriter.newLine();
    bufferedWriter.write("456");
    bufferedWriter.close();
}
@Test
public void bufferedReaderTest() throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new FileReader("file/5.txt"));

    String str;
    while ((str = bufferedReader.readLine()) != null) {
        System.out.println(str);
    }
}

十 、Apache Commons IO

导入 Apache Commons IO 的 jar 包

新建一个 Stuent 类:

package com.google.study.io;

import org.junit.experimental.theories.DataPoint;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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 "name='" + name + '\'' +
                ", age=" + age ;
    }
}

使用 Apache Comment IO 写文件:

package com.google.study.io;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

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

public class ApacheIoTest {
    @Test
    public void writeTest() throws IOException {
        File fileB = new File("file/6.txt");
        if (!fileB.exists()) {
            fileB.createNewFile();
        }

        ArrayList<Student> arrayList = new ArrayList<>();

        arrayList.add(new Student("Fleming", 123));

        // 将内容·写入文件B中
        FileUtils.writeLines(fileB, arrayList, true);

    }
}

十一、Java NIO File

进行文件拷贝、删除等可以还使用 Java NIO Files 类

Java 中实现某个目标时可以通过多种实现方式进行

我们在项目编写时可以有所取舍自行选择各种方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值