IO字节流——Java

IO概述

I表示Input,表示数据从硬盘到内存,称之为读

O表示output,表示数据从内存到硬盘,称之为写。

在这里插入图片描述

字节流可以操作所有类型的文件。

字符流只能操作纯文本文件。

步骤:

1.创建字节输出流对象。

如果文件不存在,就创建,如果文件存在就清空。

2.写数据。

写出的整数,表现在整数在码表上的数据。

3.释放资源。

每次使用完流必须要释放资源。
private static void demo01() throws IOException {
    
    
//        字节流。
        FileOutputStream fos = new FileOutputStream("E:\\a.txt", true);
        fos.write(97);
        fos.close();
}

写数据

三种方式

void write(int b) 一次写一个字节数据
void write(byte[] b) 一次写一个字节数组数据
void write(byte[] b,int off,int len) 一次写一个字节数组的部分数据
private static void demo02() throws IOException {
    
    
    FileOutputStream fos = new FileOutputStream("E:\\a.txt");
    byte[] bs = {
    
    97, 98, 99, 100};
    fos.write(bs, 1, 2);
    fos.close();
}

换行:

Windows系统:\r\n

Linux系统:\n

追加的话,需要在参数中的第二个参数写入:true,表示以追加形式打开文件。

读数据

三种方式:

read()
int len = read(byte[] b) 将读到的数据放到byte类型的b数组中,并返回读到的字节数。
read(byte[] b,int off,int len)读取byte数组中的off起始位置的len个数。

字节流读数据

private static void demo03() throws IOException {
    
    
    FileInputStream fis = new FileInputStream("E:\\a.txt");
    int b = 0;
    while ((b = fis.read()) != -1) {
    
    
        System.out.print((char) b);
    }
}

复制文件

    private static void demo04() throws IOException {
    
    
        File file = new File("E:\\a.txt");
        String path = "F:\\";
        copy(file, path);
    }

    private static void copy(File src, String path) throws IOException {
    
    
//        首先确定要复制的文件和路径
        String filename = src.getName();
        File dst = new File(path, filename);
//        读数据
        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dst);
        int i = 0;
        while ((i = fis.read()) != -1) {
    
    
//            读取数据
            fos.write(i);
        }
        fos.close();
        fis.close();
    }

使用byte数组的复制

    private static void copy(File src, String path) throws IOException {
    
    
//        首先确定要复制的文件和路径
        String filename = src.getName();
        File dst = new File(path, filename);
//        读数据
        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dst);

        byte[] b = new byte[1024];
        int len = 0;
        while ((len = fis.read(b)) != -1) {
    
    
            fos.write(b, 0, len);
        }
        fos.close();
        fis.close();
    }

总结:

写数据使用 FileOutputStream,其中的write方法。

读数据使用 FileInputStream,其中的read方法。

猜你喜欢

转载自blog.csdn.net/qq_45022687/article/details/122592594