Java基础知识02 --File类、IO流、文件读写操作与Timer定时操作

1.File类的基本使用

java.io.File 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作 。

所在包:Java.io.File

  1. File与流无关,不能通过file完成文件的读写
  2. File表示的是文件和目录路径的抽象表现形式

构造方法如下:

1.File(String path)
将一个字符串描述的路径,封装成一个 File对象。
2.File(String parent,String Child)
将两个字符串(父级路径, 子级路径),拼接之后形成的路径封装成一个File对象。
3.File(File parent, String child)
将File类型的父级路径和String类型的字节路径拼接成一个新路径,封装成File对象

1.1 创建功能

最终创建出来的是一个文件还是文件夹,不取决于路径名称,取决于调用的什么方法去创建
(1)创建文件

public boolean createNewFile() throws IOException

(2)创建文件夹

     mkdir()
          创建文件夹,如果父级路径不存在,则文件夹创建失败
     mkdirs()
          创建文件夹,如果父级路径不存在,则自动创建父级路径,再创建子级路径

1.2 删除功能

public boolean delete()

既可以删除文件,也可以删除文件夹

注意:1、删除的时候不走回收站,直接删除 2、不能删除非空文件夹

1.3 判断功能

1、exists(),判断调用者路径是否存在
2、isFile(),判断调用者是否是一个文件
3、isDirectory(),判断调用者是否是一个文件夹

2. IO流介绍

I/O,Input/Output,输入/输出
这是根据流向来进行描述的方式,究竟是输入还是输出,站在内存的角度看待问题。所有从其他设备到内存的过程,称为“输入”;所有从内存到其他设备的过程,称为“输出”。

java中操作输入输出使用的都是流对象,都是在io包中的类。

IO流有非常多,非常复杂庞大的一个体系,需要对这些类型进行分类,分类方式有两种:按照流向分类;按照能处理的数据的类型分类。

(1)按照流向:输入流、输出流
(2)按照操作数据类型:

字节流:可以直接操作字节数据(byte数据)的流对象
字符流:可以直接操作字符数据(char数据)的流对象

(3)四种顶层抽象父类

字节流:
字节输入流:InputStream
字节输出流:OutputStream
字符流:
字符输入流:Reader
字符输出流:Writer

 2.1 字节流

  • 可以直接处理字节信息的流对象
  • 计算机中一切数据都是字节数据。无论是文字、音频、图片、视频、网页等内容,底层都是字节数据
  • 字节流可以操作计算机中一切数据
  • 所有其他流对象,底层都需要依赖字节流
  • 顶层抽象父类:InputStream、OutputStream

注意:顶层父类是抽象类

2.1.1 InputStream

InputStream是字节输入流的顶层抽象父类,定义了字节输入流应该具有的功能。

常用方法:

     int read()
          返回一个字节
     int read(byte[] arr)
          将读取到的数据,存储在arr数组中
          返回的数据表示本次读取到的数据的个数
     available()
          从该流中,还能读多少字节出来
     close()
          关闭流对象

补充:

public int read(byte[] b) throws IOException

从输入流读取一些字节数,并将它们存储到缓冲区b 。 实际读取的字节数作为整数返回。 该方法阻塞直到输入数据可用,检测到文件结束或抛出异常。

如果b的长度为零,则不会读取字节并返回0 ; 否则,尝试读取至少一个字节。 如果没有字节可用,因为流在文件末尾,则返回值-1 ; 否则,读取至少一个字节并存储到b 。

(1) FileInputStream

用于和磁盘交互的字节输入流

常用构造方法:

FileInputStream(File f)
FileInputStream(String pathname)
//将File对象或者String描述的文件路径,封装成一个输入流对象

2.1.2 OutputStream

OutputStream是字节输出流的顶层抽象父类,至少应该有一个写出一个字节的方法

常用方法:

    write(int b)
          将一个字节存储到目标文件中
     write(byte[] arr)
          将参数指定的字节数组中的全部字节,写出到目标文件中
     write(byte[] arr, int offset, int len)
          将参数指定的字节数组的一部分,写出到目标文件中
          从offset索引开始,一共len个字节
     close()
          关流

(1)FileOutputStream

1、OutputStream是一个抽象的父类,不能创建对象
2、根据不同的输出设备,有不同的具体子类,写出到文件系统的文件的流对象:
FileOutputStream
3、构造方法:

FileOutputStream(String path)
FileOutputStream(File f)
//创建一个输出到指定文件中的字节输出流,如果指定文件存在,则清空
FileOutputStream(String path, boolean append)
FileOutputStream(File f, boolean append)
//创建一个输出到指定文件中的字节输出流,如果指定文件存在,append值为true,则在末尾追加

2.2 字符流

2.2.1 FileWriter

无论是字节输出流还是字符输出流都是write方法,但是字符输出流多了一个传入String对象的方法

FileWriter是用于写入字符流。

构造方法:

FileWriter(String fileName)
//构造一个给定文件名的FileWriter对象。
FileWriter(String fileName, boolean append)
//构造一个FileWriter对象,传入给定文件名,布尔值append表示是否附加写入的数据。

无论是字节输出流还是字符输出流都是write方法,但是字符输出流多了一个传入String对象的方法

public void write(String str) throws IOException
//写一个字符串

2.2.2 FileReader

FileReader是用于读取字符流。 

Reader类中没有方法可以直接读取字符串,只能通过字符数组来读取。

public int read(char[] cbuf) throws IOException
//将字符读入数组。 该方法将阻塞,直到某些输入可用,发生I / O错误或达到流的结尾。

3.文件的读写操作

3.1 进行读操作

    public static void test() {
        try {
            BufferedReader br=new BufferedReader(new FileReader("doc/user.txt"));
            String str;
            while ((str=br.readLine())!=null){
                System.out.println(str);
            }
            br.close(); //流使用完之后,一定要记得关闭;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

2.2 进行写操作

public class FileUtils {
    public static void main(String[] args) {
        inputStreamReader();
    }

    public static void inputStreamReader() {
        //1.创建输入流对象,将流理解为一只笔,输入流为读取数据,输出流为写数据
        InputStream inputStream = null;
        FileOutputStream fos=null;

        try {
            //2.实例化输入流对象
            inputStream = new FileInputStream("D:\\安装包\\1");
            //3.将读取的内容写入指定的文件夹的文件中

            //4.定义输出流的目标文件
            File file=new File("D:\\data\\1");
            //5.实例化输出流对象
            fos = new FileOutputStream(file);
            //6.指定每次读取文件的大小
            byte[] bs = new byte[1024];
            int temp=0;
            //读入多个字节到字节数组中
            while ((temp=inputStream.read(bs))!=-1){
                //7,向指定目标文件写数据,temp为一次实际读入的字节数(会实时变化)
                fos.write(bs,0,temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //8.inputStream、fos不为空,则关闭文件流
                if (inputStream != null&&fos!=null) {
                    inputStream.close();
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.3 文件批量复制

package org.jeecg.modules.util;

import java.io.*;

/**
 * 在同一个目录下,将一个文件复制成多个文件,文件名按序排列
 * @Author lucky
 * @Date 2021/11/22 9:18
 */
public class FileCopyUtil {
    public static void copyFile(String sourcePath,String targetRootPath,int copyNum){
        //1.创建输入流对象,将流理解为一只笔,输入流为读取数据,输出流为写数据
        InputStream inputStream = null;
        FileOutputStream fos=null;
        for (int i = 0; i <copyNum ; i++) {
            try {
                //2.实例化输入流对象
                inputStream = new FileInputStream(sourcePath);
                //3.将读取的内容写入指定的文件夹的文件中
                String targetPath=targetRootPath+i+".exe";
                //4.定义输出流的目标文件
                File file=new File(targetPath);
                //5.实例化输出流对象
                fos = new FileOutputStream(file);
                //6.指定每次读取文件的大小
                byte[] bs = new byte[1024];
                int temp=0;
                //读入多个字节到字节数组中
                while ((temp=inputStream.read(bs))!=-1){
                    //7,向指定目标文件写数据,temp为一次实际读入的字节数(会实时变化)
                    fos.write(bs,0,temp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    //8.inputStream、fos不为空,则关闭文件流
                    if (inputStream != null&&fos!=null) {
                        inputStream.close();
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        copyFile("D:\\data\\rabbitmq-server-3.9.7.exe", "D:\\data\\temp\\", 10);
    }
}

2.4 向已有的文件中追加写入

    /**
     * 向已有的文件中追加写入
     * @param filePath 文件路径
     */
    public static void appendWriteFile(String filePath){
        File file =new File(filePath);
        try {
            //1 创建一个文件输出流,  true:表示追加,false: 默认覆盖
            FileOutputStream fos=new FileOutputStream(file,true);
            //2 模拟执行其他任务
            long startTime=System.currentTimeMillis();
            Random random=new Random();
            Thread.sleep(100+random.nextInt(200));
            long endTime=System.currentTimeMillis();
            long executionTime=endTime-startTime;
            //3 追加写入  \r\n 表示换行。
            String temp=String.valueOf(executionTime)+"\r\n";
            fos.write(temp.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.5 批量创建文件夹

    /**
     * 批量创建文件夹
     * @param folderNum 文件夹数量
     */
    public static void createFileFolder(int folderNum){
        for (int i = 0; i <folderNum ; i++) {
            String path="D:\\data\\download\\"+i;
            File file =new File(path);
            if(!file.exists()){
                try {
                    file.mkdir();
                    log.info("文件夹: "+i+"创建成功");

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

2.6 逐行读取文件中数据,并累加

    /**
     * 逐行读取文件中数据,并累加
     * @param filePath 文件路径
     */
    public static double calculateTotalTime(String filePath){
        double totalTime=0;
        try {
            //BufferedReader是可以按行读取文件
            FileInputStream fis=new FileInputStream(filePath);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            String str=null;

            while(StringUtils.isNotBlank(str=br.readLine())){
                totalTime+=Double.parseDouble(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalTime;
    }

2.7 清空文件内容

    /**
     * 清空文件内容
     * @param filePath 文件路径
     */
    public static void cleanFile(String filePath){
        try {
            //利用FileWriter写入字符流
            FileWriter fw=new FileWriter(filePath);
            fw.write("");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

2.Timer定时操作+时间格式化输出显示

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTool {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        Timer timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                System.out.println("hellolucky");
            }
        };
        timer.schedule(timerTask,10000);

    }
}

后台输出为:

参考文献:

https://blog.csdn.net/qq_39304441/article/details/99670966

https://blog.csdn.net/zhao_miao/article/details/88368210

posted @ 2019-03-23 20:03  雨后观山色  阅读(1054)  评论(0编辑  收藏  举报