IO流

分为 字符流字节流

文件创建

​ 文件创建 在new对象时只是将其放入内存中,在执行createNewFile方法时才会将其放入磁盘

  • 根据路径创建一个File对象
//new File(String pathname)
public class Creatfile {
    public static void main(String[] args) {
        String path ="E:\\javaTest.java";
        File file = new File(path);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}    
  • 根据父目录文件+子路径构建
//new File(File parent,String child)
public class Creatfile {
    public static void main(String[] args) {
        File parentfile = new File("E:\\'这里写你已存在的文件'");
        //File parentfile = new File("E:\\代码");
        String sonName = "javaTest02.java";
        File file = new File(parentfile,sonName);
        try {
            file.createNewFile();
            //文件创建的目录就在E:\\代码\\JavaTest02.java
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//麻烦
  • 根据父目录+子路径构建
//new File(String parent,String child)
//这几种创建方式区别不大
public class Creatfile {
    public static void main(String[] args) {
        String parentfile = "E:\\代码";
        String sonName = "javaTest03.java";
        File file = new File(parentfile,sonName);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}    
  • img

读写文件

IO流中的类好多 , 最重要的流是 FileInputStreamFileOutputStream

FileInputStream

输入流

用于从文件中读取数据

//利用文件名来创建一个输入流对象来读取文件
InputStream f = new FileInputStream("文件地址");

//利用文件对象来创建一个输入流来读取文件
File f = new File("文件地址");
InputStream in = new FileInputStream(f);

InputStream对象有很多方法

  • close方法

    关闭此文件的输入流并释放于此流有关的所有资源,抛出抛出异常

  • finalize方法

    清除与该文件的连接 , 确保在不再引用文件输入流时调用 close 方法 , 抛出IOException异常

  • read(int r)方法

    InputStream对象读取指定字节的数据,返回值为整数

  • read(byte[] r) 方法

    从输入流中读取r.length长度的字节,并返回读取的字节数

  • available方法

    没理解

FileOutputStream

输出流

该类是用来创建一个文件并向该文件中写入数据

该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件

//创建一个输出流对象
OutputStream f = new FileOutputStream("文件名");

//创建一个文件对象来创建一个输出流来写文件
File f = new File("C:/java/hello");
OutputStream fOut = new FileOutputStream(f);

OutputStream对象的常用方法

  • close方法

    关闭此文件输入流并释放与此流有关的所有系统资源。抛出IOException异常。

  • finalize方法

    清除与该文件的连接 , 确保在不再引用文件输入流时调用close 方法 , 抛出IOException异常。

  • write(int w)方法

    这个方法把指定的字节写到输出流中

  • write(byte[] w)

    把指定数组中w.length长度的字节写到OutputStream中。

最后修改:2022 年 09 月 22 日
如果觉得我的文章对你有用,请随意赞赏