首页 > 编程语言 >Java中的IO流(一)

Java中的IO流(一)

时间:2023-11-09 20:57:52浏览次数:32  
标签:Java 字节 fos IO import println new String

Java中的IO流(一)

一、前言

学习这部分内容的时候,跟着敲代码难免有些乱,这里先放一张图:

二、实现对文件和文件夹的操作:

案例一:

package file.bytestream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileDemo1 {
    public static void main(String[] args) throws IOException {
        File f1 = new File("D:\\File\\test01.txt");
        System.out.println(f1);

        File f2 = new File("D:\\File","test02.txt");
        System.out.println(f2);

        File f3 = new File("D:\\File");
        File f4 = new File(f3,"test0.txt");

        //mkdirs()包含没有创建的文件夹也给创建处理啊
        //createNewFile()创建新文件
        System.out.println(f3.mkdirs());
        System.out.println(f4.createNewFile());

        //获取到文件的绝对路径
        System.out.println(f4.getAbsolutePath());
        //获取到文件路径
        System.out.println(f4.getPath());
        //获取到文件名字
        System.out.println(f4.getName());

        //判断f3是否为一个目录?
        if(f3.isDirectory()){
            String fileName;
            //循环创建多个文件
            for(int i = 1; i <= 40; i ++){
                fileName = "test" + i +".txt";
                new File(f3,fileName).createNewFile();
            }
            System.out.println("我要开始删除文件了!!!");
            deleteFile(f3);
        }

    }
    //删除文件
    public static void deleteFile(File f3){
        String fileName;
        for(int i = 0; i <= 40; i ++){
            System.out.println("我要开始删除test" + i + ".txt");
            fileName = "test" + i +".txt";
            new File(f3,fileName).delete();
        }
    }
}

案例二:

package file.bytestream;

import java.io.File;

public class FileDemo2 {
    public static void main(String[] args) {
        //绝对路劲与相对路劲
        //D:\\File\\a.txt   绝对路径
        //a.txt   相对路径
    }
}

二、字节流和字节缓存流:

这里提供一个快速记忆:
input 》》 输入 》》 向数组中输入 》》 从文件读取数据到数组中 》》 两种方法(一个一个、一个数组一个数组)

output 》》 输出 》》 从数组中输出 》》 从数组中输出数据到文件中 》》 write()

FileInputStream

例子一:

package file.bytestream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

//读取字节流
public class FileInputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //创建字节流输入流对象
        //FileInputStream(String name)
        FileInputStream fis = new FileInputStream("myByteStream\\fos01.txt");

        int by;
        /*
         * fis.read():读数据
         * by = fis.read():把读取到的数据赋值给by
         * by != -1: 判断读取到的数据是否是-1
         * */
        while((by=fis.read())!=-1){
            System.out.print((char)by);
        }

        //释放资源
        fis.close();
    }
}

例子二:

package file.bytestream;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //创建字节流输入流对象
        FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");

        byte[] bys = new byte[1024]; //1024以及整数倍
        int len;

        //循环读取
        while((len=fis.read(bys)) != -1){
            System.out.println(new String(bys,0,len));
        }

        fis.close();
    }
}

FileOutputStream

例子一:

package file.bytestream;

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

public class FileOutputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //创建字节输出流对象
        /*
        * 注意点:
        * 1、如果文件不存在,会帮我们创建
        *
        * 2、如果文件存在,会把文件清空
        * */
        //FileOutputStream(String name):创建文件输出流以指定的名称写入文件
        if(!new File("myByteStream").exists()){
            new File("myByteStream").mkdirs();
        }

        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        //void write(int b): 将指定的字节写入文件输出流
        fos.write(97);
        fos.write(57);
        fos.write(55);

        //最后释放资源
        fos.close();
    }
}

例子二:

package file.bytestream;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //FileOutputStream(String name): 创建文件输出流以指定的名称写入文件
        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        byte[] bytes = "abscsd".getBytes();
        fos.write(bytes,1,3);  //从第一个索引开始,然后3个值

        //释放资源
        fos.close();
    }
}

例子三:

这个例子和trt{}catch{}结合,在finally函数内释放资源

package file.bytestream;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo03 {
    public static void main(String[] args) {
        //加入finally来释放资源
        FileOutputStream fos = null;
        try{
            //创建字节输出对象
             fos = new FileOutputStream("myByteStream\\fos.txt");
            InputStream(fos);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void InputStream(FileOutputStream fos) throws IOException {

        //写数据
        for(int i = 0; i < 10; i++){
            fos.write("hello".getBytes());
            fos.write("\r\n".getBytes());
        }

        //释放资源
        fos.close();
    }
}

BufferedInputStream && BufferedOutputStream

package file.bytestream;

import java.io.*;

public class BufferStreamDemo {
    public static void main(String[] args) throws IOException {
        //字节缓冲输出流: BufferedOutputStream(OutputStream out)
        BufferedOutputStream bos = new BufferedOutputStream(new
                FileOutputStream("myByteStream\\bos.txt"));

        //写数据
        bos.write("hello\r\n".getBytes());
        bos.write("world\r\n".getBytes());

        //释放资源
        bos.close();

        //字节缓冲输入流:BufferedInputStream(InputStream in)
        BufferedInputStream bis = new BufferedInputStream(new
                FileInputStream("myByteStream\\bos.txt"));

        //一次读取一个字节数据
//        int by;
//        while((by = bis.read()) != -1){
//            System.out.println((char)by);
//        }

        //一次读取一个字节数组数据
        byte[] bys = new byte[1024];
        int len;
        while((len=bis.read(bys))!=-1){
            System.out.println(new String(bys,0,len));
        }

        //释放资源
        bis.close();
    }
}

三、应用

1、使用一个一个字节进行复制:

package file.bytestream;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

//字节流复制文件

/*=============================
适合txt文件
============================*/
public class CopyFileDemo {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

        copyFileByBytes(sourcePath,targetPath);
    }

    //工具函数
    public static void copyFileByBytes(String sourcePath, String targetPath){
        FileInputStream fis = null;  //输入流,将信息输入到字节数组中并存储起来
        FileOutputStream fos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //读写数据
            int by; //存储字节流(int)
            while((by = fis.read()) != -1){
                fos.write(by);
            }

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

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

2、使用一个一个数组进行复制

package file.bytestream;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

//字节流复制文件
/*=============================
适合所有文件
============================*/
public class CopyFIleDemo01 {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

        copyFileByBytes(sourcePath,targetPath);
    }

    //工具函数
    public static void copyFileByBytes(String sourcePath, String targetPath){
        FileInputStream fis = null;  //输入流,将信息输入到字节数组中并存储起来
        FileOutputStream fos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            //跟第一种使用一个一个读取字节不一样,这样做的好处是什么?
            //1、相比第一种方式使用一个字节一个字节地读取和写入,具有更高的效率。这是因为磁盘I/O操作是相对较慢的,通过一次性读取多个字节并进行批量写入,可以减少磁盘I/O操作的次数,提高数据传输的效率。
            //2、使用字节数组还可以减少内存开销,因为在Java中,一次读取多个字节并将其存储在字节数组中,可以更好地利用内存,而不是为每个字节都分配一个变量。
            byte[] bytes = new byte[1024];
            int len;
            while((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }

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

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

3、使用BufferInputStream和BufferOutputStream以及方法一和方法二进行复制:

package file.bytestream;


import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

//字节缓存流复制文件
/*=============================
适合所有文件
============================*/
public class CopyFileDemo02 {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

//        copyFileByBytes01(sourcePath,targetPath);  //字节数组读取字节流  一个数组一个数组
        copyFileByBytes02(sourcePath,targetPath); //字节流  一个一个
    }

    //工具函数
    public static void copyFileByBytes01(String sourcePath, String targetPath){
        BufferedInputStream bis = null;  //输入流,将信息输入到字节数组中并存储起来
        BufferedOutputStream bos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            bis = new BufferedInputStream(new FileInputStream(sourcePath));;
            bos = new BufferedOutputStream(new FileOutputStream(targetPath));

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            byte[] bytes = new byte[1024];
            int len;
            while((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }

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


    public static void copyFileByBytes02(String sourcePath, String targetPath){
        BufferedInputStream bis = null;  //输入流,将信息输入到字节数组中并存储起来
        BufferedOutputStream bos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            bis = new BufferedInputStream(new FileInputStream(sourcePath));;
            bos = new BufferedOutputStream(new FileOutputStream(targetPath));

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            int by; //存储字节流(int)
            while((by = bis.read()) != -1){
                bos.write(by);
            }

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

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

标签:Java,字节,fos,IO,import,println,new,String
From: https://www.cnblogs.com/new-one/p/17822788.html

相关文章

  • Educational Codeforces Round 126 (Rated for Div. 2)
    https://codeforces.com/contest/1661/B题数据很小,直接bfs预处理就行C题随便猜了一下,设mx=\(max\{a_i\}\)最后的值应该是mx,mx+1,mx+2,mx+3之类的吧D题刚开始从前面考虑,陷入僵局,一度非常的困,学习凯库勒睡了一会,就突然想到了,前面不行,就从后面考虑,可以发现,从后面考虑的话,就非常......
  • One specific Eco-Environmental Protection Measure of light pollution
     Inthissection,Iwillshowthespecificlegalmeasuresforlightpollutioninacomparativeform. ForeignlightpollutionlegislationexperienceOnlightpollution,manyforeigncountriesandregionshaveprovisionsofthelaw,theauthorslightly......
  • A solution to soil erosion
    AspecificmeasuretocopewithsoilerosionistoincreasevegetationcoverinChina.Howitworksanditsimpact:Firstly,vegetationisthefirstbarriertoprotectlandfromexternalinterference.TakeLoessPlateauasanexample,amainreasonfori......
  • Java中的多态
    向上转型后的再向下转回去才行注意:向下转型时,有可能编译阶段不报错,但是程序运行时会报错,类型转换异常。......
  • Java中的抽象类
    注意:抽象类中也是有默认的无参构造函数的eg:抽象类中的构造方法父类publicabstractclass_168AbstractParent{privateintage=300;privatefinalintcode_200=200;public_168AbstractParent(){System.out.println("我是Parent的无参构造方法......
  • Collection&Iterable
    Collection概述Therootinterfaceinthe<i>collectionhierarchy</i>.Acollectionrepresentsagroupofobjects,knownasits<i>elements</i>.Somecollectionsallowduplicateelementsandothersdonot.Someareorderedandothe......
  • 无涯教程-批处理 - Local Variables in Functions函数
    函数中的局部变量可用于避免名称冲突,并将变量更改保持在函数本地,首先使用SETLOCAL命令来确保命令处理器备份所有环境变量,可以通过调用ENDLOCAL命令来恢复变量,当到达批处理文件的末尾时,即通过调用GOTO:EOF,将自动调用ENDLOCAL。使用SETLOCAL对变量进行本地化允许在函数内自由使用......
  • 每天5道Java面试题(第6天)
    1. 接口和抽象类有什么区别?默认方法实现:抽象类可以有默认的方法实现;接口不能有默认的方法实现。实现:抽象类的子类使用构造函数:抽象类可以有构造函数,接口不能有。main方法:抽象类可以有main方法,并且我们能运行它;接口不能有main方法。实现数量:类可以实现很多个接口;但是只能继承......
  • Java登陆第二天——SQL之DML
    SQL语句SQL概括起来可以分为以下四组。(都是SQL,因为功能的不同,为了更好学习划分了类别)DDL——数据定义语言。用于定义数据的结构。指的是增,删,改数据库DML——数据操作语言。用于检索或修改数据。指的是增,删,改数据DQL——数据查询语言。用于查询各种形式的数据。指的是查询......
  • 商城系统 “牵手” 淘宝 API 接口 php java sdk
    随着互联网的快速发展,网络购物已成为人们日常生活中不可或缺的一部分。淘宝作为中国最大的电商平台之一,其商城系统中详情页面的重要性日益凸显。本文将阐述淘宝详情在商城系统中的重要性,从用户角度、商家角度和商城运营角度进行分析,并探讨如何优化详情页面,提升用户转化率和购物体验......