IO流笔记(自用)

1. IO流是什么?

在这里插入图片描述

I:Input

O:Output

通过IO可以完成硬盘文件的读和写

2. IO流的分类?

有多种分类方式:

​ 一种方式是按照流的方向进行分类:

​ 以内存作为参照物,

​ 往内存中去,叫做输入(Input)。或者叫做读

​ 从内存中出来,叫做输出(Output),或者叫做读写(Write)。

​ 另一种方式是按照读取数据方式不同进行分类:

​ 有的流是按照字节的方式读取数据,一次读取1个字节byte,等同于,一次读取8个二进制位,这种流是万能的,什么类型的文件都可以读取。包括:文本文件,图片,声音文件,视频文件等。。。。。

​ file1.txt,采用字符流的话是这样读的:a中国bc张三fe

​ 第一次读:一个字节,正好读到’a’

​ 第二次读:一个字节,正好读到’中’字符的一半。

​ 第三次读:一个字节,正好读到’中’字符的另一半。

​ 有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是为了方便读取普通文本文件而存在的,这种流不能读取:图片、声音、视频等文件。只能读取纯文本文件,连word文件都无法读取。

​ file1.txt,采用字符流的话是这样读的:a中国bc张三fe

​ 第一次读:’a‘字符(’a’字符在windows系统中占用一个字节。)

​ 第二次读:'中’字符('中’字符在windows系统中占用2个字节。)

'a'字母在windows操作系统中是一个字节。但'a'字符在java中占用两个字节,file.txt这个windows文件和java没有关系,只是windows操作系统上的普通文件。

综上所述:流的分类

​ 输入流、输出流

​ 字符流、字节流

字节流直接读取的是8个二进制位,但是字符流就可以识别了。字符流可以一个字符一个字符检测出来

3. Java中的IO流都已经写好

我们程序员不需要关心

我们最主要还是掌握在java中已经提供了哪些流,每个流的特点是什么,每个流对象上的常用方法有哪些???

java中所有的流都是在java.io.*;下。

​ java中主要还是研究:怎么new流对象。

​ 调用流对象的哪个方法是读,哪个方法是写。

4.javaIO流有四大家族

四大家族的父类

  1. Java.io.InputStream:字节输入流

  2. java.io.OutputStream:字节输出流

  3. java.io.Reade:字符输入流

  4. java.io.Writer:字符输出流

    所有的流都实现了:

    ​ java.io.Closeable接口,都是可关闭的,都要close()f方法。

    ​ 流毕竟是一个管道,这个的hi内存和硬盘之间的通道,用完流之后一定要关闭,不然会耗费(占用)很多资源。

    所有的输出流都实现了:

    ​ java.io.Flushable接口,都是可刷新的,都有flush()方法,输出流在最后输出之后,一定要记得flush()刷新一下。这个刷新表示将管道中剩余未输出的数据强行输出完(清空管道!)刷新的作用就是清空管道。

    如果没有flush()可能会丢失数据。

注意:在java中只要”类名“以Stream结尾的都是字节流。以”Reader/Writer“结尾的都是字符流

5. java.io包下需要掌握的流有16个

文件专属:

​ java.io.FileInputStream

​ java.io.FileOutputStream

​ byte数组

​ java.io.FileReader

​ java.io.FileWriter

​ char数组

转换流:将字节流转换为字符流的

​ java.io.InputStreamReader

​ java.io.OutputStreamWriter

缓冲流专属

​ java.io.BufferedReader

​ java.io.BufferedWriter

​ java.io.BufferedInputStream

​ java.io.BufferedOutputStream

数据流专属

​ java.io.DataInputStream

​ java.io.DataOutputStream

标准输出流

​ java.io.PrintWriter

​ java.io.PrintStream

对象专属流:

​ java.io.ObjectInputStream

​ java.io.ObjectOutputStream

6. FileInputStream(文件字节输入流)(掌握)

6.1 使用程序实现文件字节输入流读取文件数据

虽然万能,但一次拿一个字节,效率比较低

package com.company.java.io;
/*
*java.io.FileInputStream:
* 1、文件字节输入流,万能的,任何类型文件都可以采用这个流来读。
* 2、字节的方式,完成输入的操作,完成读的操作(从硬盘到内存)
* */

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

public class FileInputStreamTest01 {
    public static void main(String[] args)  {
        //创建文件字节输入流对象
        //文件路径D:\temp(IDEA会自动把\编程\\,因为在java中\表示转义)
        //写成/也行
        FileInputStream fis = null;
        try {
             fis = new FileInputStream("D:\\temp");

             //开始读
            int readData = fis.read();//这个方法的返回值是:读取到的”字节“本身。
            System.out.println(readData);//97

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //在finally语句快中确保流一定关闭。
            if (fis == null) {//避免空指针异常
                //关闭前提是:流不是空。流是null没必要关闭
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

将上面代码的循环进行改进

package com.company.java.io;

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

/*
* 对第一个程序循环进行改进。
* */
public class FileInputStreamTest02 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\temp");
            /*while(true){
                int readDate = fis.read();
                if(readDate == -1){
                    break;
                }else{
                    System.out.println(readDate);
                }
            }*/
            //改造while循环
            int readDate = 0;
            while((readDate = fis.read()) != -1){
                System.out.println(readDate);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

文件路径使用相对路径,IDEA文件的默认路径是为project的根。

package com.company.java.io;

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

/*
int read(byte[] b)
一次最多读取b.length个字节,减少硬盘和内存的交互,提高程序的执行效率。
往byte[]数组当中读。
*/
public class FileInputStreamTest03 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //相对路径的话呢?相对路径一定是从当前所在位置作为起点开始找!
            //IDEA默认当前位置在哪?——工程project的根就是IDEA的默认当前路径。
            fis = new FileInputStream("temp.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

采用byte数组,一次读取多个字节,最多读取 数组.length个字节

package com.company.java.io;



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

/*
int read(byte[] b)
一次最多读取b.length个字节,减少硬盘和内存的交互,提高程序的执行效率。
往byte[]数组当中读。
*/
public class FileInputStreamTest03 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //相对路径的话呢?相对路径一定是从当前所在位置作为起点开始找!
            //IDEA默认当前位置在哪?——工程project的根就是IDEA的默认当前路径。
            fis = new FileInputStream("temp.txt");
            byte[] bytes = new byte[4];//准备一个4个长度的byte数组,一次最多读取4个字节。
            
            //使用循环将数组内容转化为字符串
            while(true){
                int readCount = fis.read(bytes);
                System.out.println(new String(bytes,0,readCount));
                if(readCount < bytes.length){
                    break;
                }
                
            }
            
            //这个字节读取到的返回值是读到的字节数量(不是字节本身)
            int readCount = fis.read(bytes);//第一次读到四个字节
            System.out.println(readCount);//4


            //将字节数组全部转换为字符串,不应该全部都转换,应该读取了多少个就转多少个
            //
            System.out.println(new String(bytes,0,readCount));
/*            String s = new String(bytes);
            System.out.println(s);*/

            readCount = fis.read(bytes);//第二次只读到3个字节
            System.out.println(readCount);//3
            System.out.println(new String(bytes,0,readCount));
/*            s = new String(bytes);
            System.out.println(s);*/

            readCount = fis.read(bytes);//第三次一个字节都没读到
            System.out.println(readCount);//-1

/*            s = new String(bytes);
            System.out.println(s);*/
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileInputStream最终

package com.company.java.io;

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

public class FileInputStreamTest04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("temp.txt");
            byte[] bytes = new byte[4];
            
            while(true){
                int readCount = fis.read(bytes);
                
                if(readCount == -1//< bytes.length){
                    break;
                }else{
                    System.out.println(new String(bytes,0,readCount));
                }

            }

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

循环再改进

int readCount = 0;
    while ((readCount = fis.read(bytes)) != -1){
        System.out.print(new String(bytes,0,readCount));
    }

6.2 FileInputStream 其他常用方法(掌握)

int available(); 返回流当中剩余的字节数量

package com.company.java.io;

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

/*
*FileInputStream其他常用方法
*
*
* */
public class FileInputStreamTest05 {
    public static void main(String[] args)  {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("temp.txt");
            int readByte = fis.read();
            System.out.println("还剩" + fis.available() + "字节没读");
            //作用:byte[] b = new byte[fis.available()];用来确定数组长度,
            // 之后读取就不需要循环了,
            // 直接读一次就可以获取文件中的所有内容
            //这种方式,不太适合太大的文件,因为byte数组不能太大
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

long skip(long n); 跳过几个字节不读

public class FileInputStreamTest05 {
    public static void main(String[] args)  {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("temp.txt");
            fis.skip(3);//跳过三个字节不读
            System.out.println(fis.read());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

7. FileOutputStream文件字节输出流

如果文件不存在会新建一个

package com.company.java.io;

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

/*
* 文件字节输出流,负责写
* 从内存到硬盘
* */
public class FileOutputStreamTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //myfile文件不存在的时候会自动新建
            fos = new FileOutputStream("myfile");
            //开始写
            byte[] b = {97,98,99,100};
            //将b数组全部写出!
            fos.write(b);

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

**7.1 将字符串转化为byte数组写入到硬盘中,在文件末尾追加不覆盖源文件内容 **

package com.company.java.io;


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


public class FileOutputStreamTest01 {
    public static void main(String[] args) {

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("temp.txt",true);
            String s = "我是中国人!";
            byte[] bs = s.getBytes();
            fos.write(bs);
            fos.flush();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

现存问题:从硬盘读入内存是乱码

7.2 文件复制

package com.company.java.io;

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

/*
* 使用FileInputStream和FileOutputStream实现文件的拷贝
* 拷贝的过程应该是一边读一边写,使用以上的字节流拷贝文件的时候,文件类型随意,万能的,什么样的文件都能拷贝
* */
public class Copy01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            //创建一个输入流对象
            fis = new FileInputStream("E:\\Downloads\\新员工培养计划表(模板).xlsx");
            //创建一个输出流对象
            fos = new FileOutputStream("D:\\新员工培养计划表(模板).xlsx");

            //一边读一边写
            byte[] bytes = new byte[1024 * 1024];//一次最多拷贝1兆
            int readData = 0;
            while((readData = fis.read(bytes)) != -1){
                fos.write(bytes,0,readData);
            }
            //刷新,输出流最后要刷新
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //分开try不要一起try
            // 两个关闭放在一个try里会产生前一个流异常后面的流也无法关闭的情况!
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

8. FileReader

8.1 用FileReader读普通文本文件

package com.company.java.io;
/*
* FileReader:
*       文件字符输入流,只能读取普通文本;
*       读取文本内容时,比较方便,快捷
*
* */

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest01 {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            //创建文件字符输入流对象
            fr = new FileReader("temp.txt");
            //开始读
/*            char[] chars = new char[4];//一次读取4个字符
            int readData = 0;
            while((readData = fr.read(chars)) != -1){
                System.out.print(new String(chars,0,readData));
            }*/
            //准备一个char数组
            char[] chars = new char[4];
            //往char数组中读
            fr.read(chars);
            for (char c : chars) {
                System.out.println(c);
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

9. FileWriter

9.1 用FileWriter向普通文本文件中写入内容

package com.company.java.io;

import java.io.FileWriter;
import java.io.IOException;

/*
* FileWriter:
*       文件字符输出流,写
*       只能输出文本
*
* */
public class FileWriterTest {
    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            //创建文件字符输出流对象
            writer = new FileWriter("temp.txt",true);
            //开始写
            String s= "学习java很快乐!";
            writer.write(s);
            
            char[] chars = {'a','b','c','d'};
            writer.write(chars);

            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

9.2 复制普通文本文件

package com.company.java.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Copy02 {
    public static void main(String[] args) {
        FileReader reader = null;
        FileWriter writer = null;

        try {
            reader = new FileReader("D:\\新建文本文档.txt");
            writer = new FileWriter("E:\\新建文本文档.txt");

            char[] chars= new char[10];
            int readData = 0;
            while((readData = reader.read(chars)) != -1){
                writer.write(chars,0,readData);
            }
            writer.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

10. BuferedWriter

package com.company.java.io;

import java.io.*;

public class BufferedWriterTest01 {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            /*fw = new FileWriter("temp.txt");
            BufferedWriter out = new BufferedWriter(fw);*/

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("temp.txt")));


            out.write("sjjdijiejij");
            out.write("景帝即位");

            out.flush();
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

11. BufferedReader

package com.company.java.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/*
* BufferedReader:
*   带有缓冲区的字符输入流
*   使用这个流的时候不需要自定义char数组,或者不需要自定义byte数组。自带缓冲区
*
* */
public class BufferedReaderTeat01 {
    public static void main(String[] args) {
        try {
            //当一个流的构造方法中需要一个流的时候,这个被传进来的流叫:节点流。
            //外部负责包装的这个流,叫做:包装流,还有一个名字叫做处理流。
            //像当前这个程序来说,FileReader就是节点流,BufferedReader就是包装流。
            FileReader reader = new FileReader("temp.txt");
            BufferedReader br = new BufferedReader(reader);

            //读取一行
            /*String s = br.readLine();
            System.out.println(s);
*/
            //br.readLine()方法,读取一个文本行,不带换行符
            String s = null;
            while((s = br.readLine()) != null){
                System.out.println(s);
            }

            //关闭流
            br.close();
            //对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

11.1 字节流转换为字节流

package com.company.java.io;
/*
* 转换流:InputStreamReader
*
* */
import java.io.*;

public class BufferedReaderTeat02 {
    public static void main(String[] args) {
        try {
/*            //字节流
            FileInputStream in = new FileInputStream("Copy02.java");

            //通过转换流转换
            //in是节点流,ir是包装流
            InputStreamReader ir = new InputStreamReader(in);

            //这个构造方法只能传字符流不能传字节流
            //ir是节点流,br是包装流
            BufferedReader br = new BufferedReader(ir);*/

            //合并
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream("temp.txt")));
            String s = null;
            while((s = br.readLine()) != null){
                System.out.println(s);
            }
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

12. 数据流

12.1 DataOutputStream

package com.company.java.io;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/*
* Java.io.DataOutputStream:数据专属的流
* 这个流可以将数据连同数据的类型一起写入文件
* 注意:这个文件不是个普通文档(用记事本打不开)
*
* */
public class DataOutputStreamTest {
    public static void main(String[] args) throws Exception {
        //创建数据专属的字节输出流
        DataOutputStream dos = new DataOutputStream( new FileOutputStream("data"));
        //写数据
        byte b = 100;
        short s  = 200;
        char c = 'a';
        boolean bo = true;
        int i = 300;
        long l = 400L;
        float f = 3.14F;
        double d = 3.14;
        //写
        dos.writeByte(b);//把数据和数据类型一并写入文件中
        dos.writeShort(s);
        dos.writeChar(c);
        dos.writeBoolean(bo);
        dos.writeInt(i);
        dos.writeLong(l);
        dos.writeFloat(f);
        dos.writeDouble(d);

        //刷新
        dos.flush();
        dos.close();
    }
}

12.2 DataInputStream

package com.company.java.io;

import java.io.DataInputStream;
import java.io.FileInputStream;

/*
* DataInputStream:数据字节输入流。
* DataOutputStream:数据字节输出流。写的文件只能用DataInputStream去读,并且读的时候你需要提前知道写的顺序。
* 读的顺序要和写的顺序一致才能取出数据
* */
public class DateInputStreamTest {
    public static void main(String[] args) throws Exception{
        DataInputStream dis = new DataInputStream(new FileInputStream("data"));

        byte b = dis.readByte();
        short s  = dis.readShort();
        char c = dis.readChar();
        boolean bo = dis.readBoolean();
        int i = dis.readInt();
        long l = dis.readLong();
        float f = dis.readFloat();
        double d = dis.readDouble();

        System.out.println(b);
        System.out.println(s);
        System.out.println(c);
        System.out.println(bo);
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);
    }
}

DataOutputStream和DataInputStream之间的关系:DataOutputStream用什么样的顺序写DataInputStream就用什么样的顺序读。否则是读不出来的

13.标准输出流(以PrintStream为例)(掌握)

package com.company.java.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
* 日志工具*/
public class Logger {
/*
* 记录日志的工具类
* */
    public static void log(String msg) throws Exception {
        //指向一个日志文件
        PrintStream out = new PrintStream(new FileOutputStream("log.txt",true));
        //改变输出方向
        System.setOut(out);
        //r
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String strTime = sdf.format(nowTime);
        System.out.println(strTime + ":" + msg);
    }
}

测试类

package com.company.java.io;

public class LogTest {
    public static void main(String[] args) throws Exception {
        //测试工具类是否好用
        Logger.log("调用了System类的gc()方法");
    }
}

14. 对象专属流(掌握)

Java.io.ObjectInputStream

java.io.ObjectOutputStream

15. java.io.File类的理解

File类的常用方法

File.exists();//判断文件是否存在
File.createNewFile();//新建一个文件
File.mkdir();//新建一个文件夹
File.mkdirs();//新建多重文件夹
String s = File.getParent();//获取文件的父路径,以字符串的格式返回
File file = File.getAbsolutePath();//获取文件的上层路径,以文件的格式返回

方法使用实例

package com.company.java.io;

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

/*
* File文件和路径名的抽象表示形式
* File类和四大家族没有关系,所以File类不能完成文件的读和写
*E:\JAVA学习资料
* E:\JAVA学习资料\JAVA-WEB\1、课程视频\1.2、JAVAEE之JAVAWEB\2、后端\Linux
*       \安装软件CentOS-6.7-x86_64-bin-DVD1 (1).iso也是一个File对象
* 一个File对象有可能是对应的目录
* */
public class FileTest01 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\hello!\\world!");
        //判断文件是否存在
        System.out.println(file.exists());
        /*
        * 判断文件是否存在。如果不存在新建一个文件
        * */
/*        if(!file.exists()){
            file.createNewFile();
        }*/
        //判断文件是否存在,如果不存在,新建一个文件夹
        if(!file.exists()){
            file.mkdir();
        }
        //判断文件是否存在,如果不存在创建多重目录;
        if(!file.exists()){
            file.mkdirs();
        }

        //获取父路径
        //以字符串的形式返回
        String s = file.getParent();
        System.out.println(s);

        //以File的格式返回父类路径
        File parentpath = file.getParentFile();
        System.out.println(parentpath.getAbsolutePath());
    }
}

常用方法2

File.length();//返回文件大小,单位是字节
File.getName();//获取文件名称
File.isFile();//判断file是否是一个文件
File.isDriectory();//判断file是否是一个目录
File.lastModified();//最后一次修改时间

方法示例

package com.company.java.io;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
*
* File类的常用方法*/
public class FileTest02 {
    public static void main(String[] args) {
        File file1 = new File("E:\\JAVA学习资料\\JAVA-SE\\JAVA核心基础\\2、Java-OOP\\第四章\\授课讲义\\第四章 JAVA-OOP(四).pdf");
        //获取文件名
        String name = file1.getName();
        System.out.println(name);

        //判断file1是否是一个目录
        System.out.println(file1.isDirectory());
        //判断file1是否是一个文件
        System.out.println(file1.isFile());

        //获取文件的最后一次修改时间
        long ms = file1.lastModified();//这个毫秒是从1970年开始到现在的毫秒数

        //将总毫秒数转换成日期
        Date time = new Date(ms);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String format = simpleDateFormat.format(time);
        System.out.println(format);


        //获取文件大小,单位是字节
        System.out.println(file1.length());
    }
}

File.listFiles():获取目录下的子文件

package com.company.java.io;

import java.io.File;

/*
* File中的listFiles方法
* */
public class FileTest03 {
    public static void main(String[] args) {
        //File[] listFiles(
        //获取当前目录下的所有的子文件
        File file1 = new File("E:\\JAVA学习资料\\JAVA-SE\\JAVA核心基础\\2、Java-OOP\\第四章");
        File[] files = file1.listFiles();
        for (File file:files) {
            System.out.println(file);
            System.out.println(file.getName());
        }
    }
}

拷贝目录

存在问题:部分文件无法拷贝,控制台显示(系统找不到指定的路径。)

package com.company.java.io;
/*
* 拷贝目录
* */


import java.io.*;

public class CopyDir {
    public static void main(String[] args) throws IOException {
        //要拷贝的目录
        File file1 = new File("E:\\JAVA学习资料\\JAVA-SE\\JAVA核心基础");
        //目标目录
        File file2 = new File("D:\\");
        //调用方法拷贝
        copyDirs.copy(file1,file2);
    }
}



/*
*
* 拷贝目录
* */
class  copyDirs{
    public static void copy(File file1, File file2) throws IOException {

        //如果文件file1是文件不是目录将不进入循环
        if(file1.isFile()){
            FileOutputStream ous = null;
            FileInputStream ins = null;
            //如果是个文件的话拷贝到目标文件中递归结束
            try {
                ins = new FileInputStream(file1);
                //((file2.getAbsolutePath().endsWith("\\") ? file2.getAbsolutePath() : file2.getAbsolutePath() + "/" ) + file1path.substring(3));
                //目标路径如何确定
                //确定源文件的绝对路径
                String path = file1.getAbsolutePath();
                //将源文件的盘符截掉,从第三个字符开始拼接在要复制的目标文件绝对路径后
                String path2 = (file2.getAbsolutePath().endsWith("\\") ? file2.getAbsolutePath() : file2.getAbsolutePath() + "/" ) + path.substring(3);
                //创建输出流对象
                ous = new FileOutputStream(path2);

                int readDate = 0;
                byte[] bytes = new byte[1024 * 1024];
                while((readDate = ins.read(bytes)) != -1){
                    
                    ous.write(bytes,0,readDate);
                }
                ous.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (ous != null) {
                    try {
                        ous.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if(ins != null){
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }

        //获取源下面的子目录。通过file.listFile或群文件下的所有子文件
        File[] files = file1.listFiles();
        for (File file:files) {
            //如果是一个目录
            if(file.isDirectory()){
                //获取源文件的绝对路径
                String file1path = file1.getAbsolutePath();
                //将源文件路径加在目标文件的路径后面
                String file2path = ((file2.getAbsolutePath().endsWith("\\") ? file2.getAbsolutePath() : file2.getAbsolutePath() + "/" ) + file1path.substring(3));
                //使用新加的路径构建File对象
                File newFile = new File(file2path);
                //如果创建的文件对象不存在,新建一个多层目录
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            //递归调用
            copy(file,file2);
        }
    }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值