IO读写再理解

一、背景

之前对IO文件读写这部分一直是半懂状态,啥意思呢?也能写文件的读写,知道有啥函数能干啥,但是还是有点懵,特别是以二进制方式读取文件(图像)等不太明白。最近在看操作系统(Operating System),接触了Linux系统编程,看了C语言中read()write()的使用才有进一步的理解。

二、实验

C语言中IO读写所对应的函数是read()write(),无论是读还是写都会用到一个buf缓冲数组作为中间桥梁。如在读文件时,read是从缓冲内存中进行读取;写文件先从缓冲流中取之后再进行写操作。

/**
* Linux下的模拟cp命令完成文件的复制核心代码
*/
// 定义缓存大小
#define BUFF_SIZE 1024

char *fis = "input path";
char *fos = "output path";
// 输入文件
int inFd = open(fis, O_RDONLY);
if (inFd == -1) 
    exit(1);
// 输出文件
int outFd = open(fos, O_CREAT | O_RDONLY, 0777);
if (outFd == -1)
    exit(1);
// 读文件
char buf[BUFF_SIZE];
int hasRead;
while ((hasRead = read(inFd, buf, BUFF_SIZE)) > 0)
{
    int hasWrite = write(outFd, buf, hasRead); // 每次写的数量等于读的数量
    if (hasWrite == -1) {
        fprintf(stderr, "Write Error!\n");
        exit(1);
    }
}
close(inFd);
close(outFd);

理解了C语言的文件操作方式,写Java时就会更方便。

public class IODemo {
    public static void main(String[] args) {
        String inputFile = "1.txt";
        String file = "2.txt";
        // 不存在则创建目标文件
        File outFile = new File(file);
        if (!outFile.exists()) {
            try {
                outFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outFile);
             // 缓存流方式读写
             BufferedInputStream bis = new BufferedInputStream(fis);
             BufferedOutputStream bos = new BufferedOutputStream(fos)
        ) {
            byte[] buf = new byte[1024];
            int hasRead;
            while ((hasRead = bis.read(buf)) != -1) {
                bos.write(buf, 0, hasRead);  // 读多少写多少
            }
            System.out.println("copy has done!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当然Java也是支持以字符方式进行读写,一般适用文字场景。以前不太喜欢二进制方式读写,主要还是理解的不够,二进制是一种通用的IO读写方式,不仅对文本适用,图像的本质也是二进制,二进制的IO读写方式当然对图像也是适用的,只需要换成图像名字就行。

posted @ 2021-04-23 21:11  Maverickos  阅读(146)  评论(0编辑  收藏  举报