字节流

HeJin大约 4 分钟JavaIO流

字节输入流

所有字节输入流的父类是java.io.InputStream,它是以字节为单位的输入流。

FileInputStream

对象创建

public FileInputStream(String name) throws FileNotFoundException

public FileInputStream(File file) throws FileNotFoundException 

读取文件

  • 一次读取一个字节

    // 读取一个字节的数据作为返回值返回
    public int read() throws IOException
    

    使用:

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("io/src/main/java/com/a.txt");
    
        // 读取数据
        int b;
        while ((b = fis.read()) != -1){
            System.out.println(b);
        }
    
        // 释放资源
        fis.close();
    }
    

    a.txt:

    abbcdd
    

    结果:

    97
    98
    98
    99
    100
    100
    
    Process finished with exit code 0
    
  • 一次读取一个字节数组

    // 传入一个字节数组,最多读取一个字节数组的数据,并且会把数据存入数组中,返回值代表本次读取到的字节的个数
    // 返回值为-1,代表没有数据了
    public int read(byte b[]) throws IOException
       
    // 传入一个字节数组,读取len个长度的数据,并且存入数组中从off开始的len个长度
    // 返回值代表本次读取到的字节的个数 
    public int read(byte b[], int off, int len) throws IOException    
    

    使用:

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("io/src/main/java/com/a.txt");
    
        // 读取数据:一次读取4个字节
        byte[] bytes = new byte[4];
        int len;
        while ((len = fis.read(bytes)) != -1){
            System.out.println(new String(bytes, 0, len));
        }
    
        // 释放资源
        fis.close();
    }
    

    结果:

    abbc
    dd
    
    Process finished with exit code 0异常处理JDK
    

异常处理

  • JDK1.6

    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("io/src/main/java/com/a.txt");
            // 读取数据:一次读取4个字节
            byte[] bytes = new byte[4];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if(fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • JDK1.7:try的后面加个小括号,定义资源,调用完成后会自动释放。

    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("io/src/main/java/com/a.txt")) {
            // 读取数据:一次读取4个字节
            byte[] bytes = new byte[4];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

字节输出流

FileOutputStream

所有字节输入流的父类是java.io.OutputStream,它是以字节为单位的输出流。

创建对象

public FileOutputStream(String name) throws FileNotFoundException 

public FileOutputStream(File file) throws FileNotFoundException   
  

写数据

  • 一次写一个字节

    public void write(int b) throws IOException
    
    public static void main(String[] args) throws IOException {
        File file = new File("io/src/main/java/com/out.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write('a');
        fos.write('b');
        fos.write('c');
        fos.write('d');
    
        fos.close();
    }
    
  • 一次写一个字节数组

    // 传入一个字节数组,把数组中的全部数据写入文件
    public void write(byte b[]) throws IOException
    
    // 传入一个字节数组,把数组中从off开始的len个长度的数据写入文件    
    public void write(byte b[], int off, int len) throws IOException    
    
    public static void main(String[] args) throws IOException {
        File file = new File("io/src/main/java/com/out.txt");
        FileOutputStream fos = new FileOutputStream(file);
    
        byte[] bytes = new byte[]{'a', 'b', 'c', 'd', 'e'};
        // 文件中写入:bcde
        fos.write(bytes, 1, 4);
    
        fos.close();
    }
    

文件续写

对于一个输出流,在关闭的时候结束对文件的写入。流的完成操作流程是从创建流对象到关闭流对象。

// 第二个参数代表是否续写
public FileOutputStream(String name, boolean append)
    
// 第二个参数代表是否续写    
public FileOutputStream(File file, boolean append)    
  • 覆盖写入

    public static void main(String[] args) throws IOException {
        File file = new File("io/src/main/java/com/out.txt");
        writeToFile(file, "123".getBytes());
        writeToFile(file, "abc".getBytes());
    }
    
    private static void writeToFile(File file, byte[] bytes) throws IOException {
        // 覆盖写入
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);
        fos.close();
    }
    
  • 追加写入

    public static void main(String[] args) throws IOException {
        File file = new File("io/src/main/java/com/out.txt");
        writeToFile(file, "123".getBytes());
        writeToFile(file, "abc".getBytes());
    }
    
    private static void writeToFile(File file, byte[] bytes) throws IOException {
        // 追加写入
        FileOutputStream fos = new FileOutputStream(file, true);
        fos.write(bytes);
        fos.close();
    }
    

文件复制

要求定义一个方法,可以实现文件的复制。

/**
 * 复制文件
 * @param srcFile 源文件
 * @param destDir 目标文件夹
 * @throws IOException 异常
 */
public static void copyFile(File srcFile, File destDir) throws IOException {
    if(!srcFile.isFile()){
        throw new RuntimeException("源文件非法!!!");
    }
    if(!destDir.isDirectory()){
        throw new RuntimeException("目标文件夹非法!!!");
    }
    
    // 在目标文件夹创建文件
    File destFile = new File(destDir, srcFile.getName());
    // 创建输入输出流,循环读写
    FileInputStream inputStream = new FileInputStream(srcFile);
    FileOutputStream outputStream = new FileOutputStream(destFile);

    byte[] bytes = new byte[1024];
    int len;
    while ((len = inputStream.read(bytes)) != -1){
        outputStream.write(bytes, 0, len);
    }

    inputStream.close();
    outputStream.close();
}

文件夹复制

要求定义一个方法,可以实现文件夹的复制。

/**
 * 复制目录
 * @param srcDir 源文件夹
 * @param destDir 目标文件夹
 */
public static void copyDir(File srcDir, File destDir) throws IOException {
    if(!srcDir.isDirectory()){
        throw new RuntimeException("源文件夹非法!!!");
    }
    if(!destDir.isDirectory()){
        throw new RuntimeException("目标文件夹非法!!!");
    }

    // 在目标文件夹创建目录
    File dest = new File(destDir, srcDir.getName());
    dest.mkdirs();

    // 遍历源文件夹
    File[] files = srcDir.listFiles();
    if(files == null){
        return;
    }
    for (File file : files) {
        if(file.isFile()){
            // 复制文件
            copyFile(file, dest);
        } else {
            // 递归调用复制目录
            copyDir(file, dest);
        }
    }
}