第31天学习打卡(File类、字符流读写文件)

File类

概念

文件,文件夹,一个file对象代表磁盘上的某个文件或者文件夹

构造方法

File(String pathname)
File(String parent,String child)
File(File parent, String child)

成员方法

creatNewFile():创建文件
mkdir()mkdirs():创建目录(即创建文件夹)
isDirectory():判断File对象是否为目录
isFile():判断File对象是否为文件
exicts():判断File对象是否存在
package cn.itcast.demo20;
/*
File类:
    概述:
       文件,文件夹,一个File对象代表磁盘上的某个文件夹。也就是用来操作文件(夹)路径的。
    构造方法:
        File(String pathname) 根据给定的字符串路径创建其对应的File对象
        File(String parent, String child)根据给定的字符串形式的父目录和子文件(夹)名创建File对象
        File(File parent, String child)根据给定的父母目录对象和子文件(夹)名创建File对象
    成员方法:
        创建功能:如果不存在就创建,返回true,否则就不存在,返回false
             createNewFile():创建文件夹
             mkdir(): 创建单级目录
             mkdirs():创建目录
        判断功能:
             isDirectory():判断File对象是否为目录
             isFile():判断File对象是否为文件
             exists():判断File对象是否存在

 */

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

public class Test {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求: 将 D:\abc\1.txt 封装成File对象.
        //方式一: 根据字符串形式的路径获取File对象.
        //File file1 = new File("D:\\abc\\1.txt");
        File file1 = new File("D:/abc/1.txt");
        System.out.println("file1: " + file1);

        //方式二: 根据字符串形式的父目录以及子目录创建File对象.
        File file2 = new File("D:/abc/", "1.txt");
        System.out.println("file2: " + file2);

        //方式三: 根据父目录对象, 以及字符串形式的子目录来获取File对象.
        File file3 = new File("D:/abc/");
        File file4 = new File(file3, "1.txt");
        System.out.println("file4: " + file4);
        System.out.println("-----------------------------");
        System.out.println("创建功能");
        //需求: 在f:盘下创建 b.txt文件(我的在D盘里面创建不了b.txt 文件,会报错, 所有要换一个文件的路径改为f盘或者其他盘。不区分盘的大小写)
        File file5 = new File("f:/b.txt");
        boolean flag1 = file5.createNewFile();
        System.out.println("flag1: " + flag1);

        //需求: 在D:盘下创建 a文件夹
       File file6 = new File("D:/a");
       boolean flag2 = file6.mkdir();//make directory:创建单级目录
        System.out.println("flag2:" + flag2);

        //需求:在D盘创建a/b/c文件夹:即文件夹a下包含文件夹b,文件夹b下包含文件夹c.即创建多级路径
        File file7 = new File("D:/a/b/c");
        boolean flag3 = file7.mkdirs();//mkdirs可以创建多级目录也可以创建单级目录
        System.out.println("flag3:" + flag3);

        System.out.println("==============");
        System.out.println("测试判断功能");
        File file8 = new File("D:/a/b");
       /* boolean flag4 = file8.isDirectory();
        System.out.println("测试file8是否是文件夹:" + flag4);*/
        //上面注释的是标准的写法
        System.out.println("测试file8是否是文件夹:" + file8.isDirectory());
        System.out.println("测试file8是否是文件:" +file8.isFile());
        System.out.println("测试file8是否是存在:" + file8.exists());

    }
}

成员方法

getAbsolutePath():获取绝对路径
绝对路径:以盘符开头的路径
例如:D:/1.txt
getPath():获取文件的相对路径
相对路径:一般是相对于当前项目路径来讲的。
例如:1.txt
getName():获取文件名
list():获取指定目录下所有文件(夹)名称数组
listFiles():获取指定目录下所有文件(夹)File数组
package cn.itcast.demo21;
/*
File类的获取功能:
        getAbsolutePath():获取绝对路径
        getPath():获取文件的相对路径
        getName():获取指定目录下所有文件(夹)名称数组
        list():获取指定目录下所有文件(夹)File数组
        listFile():获取指定目录下所有文件(夹)File数组
Java中路径的划分:
        绝对路径:
             以盘符开头的路径,固定的,写“死”的路径
        相对路径:
             意思是相对某个路径而言,Java中的相对路径是指:相对于当前项目的路径来讲的
 */

import java.io.File;

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

        File file1 = new File("lib/1.txt");

        //获取file1的绝对路径
       String path1 = file1.getAbsolutePath();
        System.out.println("绝对路径: " + path1);


        //获取file1的相对路径
        String path2 = file1.getPath();
        System.out.println("相对路径:" + path2);

        //获取文件名
        String fileName = file1.getName();
        System.out.println("文件名:" + fileName);

        //获取lib文件夹下所有的文件(夹)的:名称数组String[]
        File file2 = new File("lib");
        String[] names = file2.list();
        for (String name : names){
    
    
            System.out.println(name);
        }
        System.out.println("==================");

        //获取lib文件夹下所有的文件(夹)的:File对象数组File[]
        File[] files= file2.listFiles();
        for(File file:files){
    
    
            System.out.println(file);

        }

    }
}

输出结果:

绝对路径: C:\Users\HP\Desktop\besttj\lib\1.txt
相对路径:lib\1.txt
文件名:1.txt
1.txt
a

abc

lib\1.txt
lib\a
lib\abc

Process finished with exit code 0

字符流读写文件

字符流读数据-按单个字符读取

image-20210208113357772

创建字符流读文件对象:
Reader reader = new FileReader("readme.txt");
调用方法读取数据:
int data = reader.read();

读取一个字符,返回该字符代表的整数,若到达流的末尾,返回-1

异常处理:
throws IOException
关闭资源:
reader.close();
package cn.itcast.demo22;
/*
字符流读数据:
      Reader 类中的方法:
              int read(): 读一个字符,返回该字符对应的ASCII码值,读不到返回-1
      FileReader类的构造方法:
               public FileReader(String pathname):根据传入的字符串形式的路径,获取字符输入流对象

 */

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

public class ReaderDemo01 {
    
    
    public static void main(String[] args) throws FileNotFoundException, IOException {
    
    
        //需求:通过字符流读取数据
        //1.创建字符输入流对象
        Reader reader = new FileReader("lib/1.txt");


        //2.读取数据
        int ch1 = reader.read();
        System.out.println(ch1);//输出了lib/1.txt文件中abc 中a的ascii值97

        int ch2 = reader.read();
        System.out.println(ch2);//输出了lib/1.txt文件中abc 中b的ascii值98

        int ch3 = reader.read();
        System.out.println(ch3);//输出了lib/1.txt文件中abc 中c的ascii值99

        int ch4 = reader.read();
        System.out.println(ch4);//输出-1,因为已经到字符串末尾了


        //3.释放资源
        reader.close();
    }
}

package cn.itcast.demo22;
/*
字符流读数据:
      Reader 类中的方法:
              int read(): 读一个字符,返回该字符对应的ASCII码值,读不到返回-1
      FileReader类的构造方法:
               public FileReader(String pathname):根据传入的字符串形式的路径,获取字符输入流对象

 */

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

public class ReaderDemo01 {
    
    
    public static void main(String[] args) throws FileNotFoundException, IOException {
    
    
        //需求:通过字符流读取数据
        //1.创建字符输入流对象
        Reader reader = new FileReader("lib/1.txt");


        //2.读取数据
        /*int ch1 = reader.read();
        System.out.println(ch1);//输出了lib/1.txt文件中abc 中a的ascii值97

        int ch2 = reader.read();
        System.out.println(ch2);//输出了lib/1.txt文件中abc 中b的ascii值98

        int ch3 = reader.read();
        System.out.println(ch3);//输出了lib/1.txt文件中abc 中c的ascii值99

        int ch4 = reader.read();
        System.out.println(ch4);//输出-1,因为已经到字符串末尾了*/
        /*
        优化上述的读法,用循环改进
        又因为不知道循环的次数,所有用while循环
         */
        //定义变量,用来接收读取到的字符
        int ch;
        /*
        (ch=reader.read())!= -1 这句代码做了三件事
               1.执行reader.read() 去文件中读取一个字符
               2.执行ch=reader.read()将读取到的字符赋值变量
               3.(ch=reader.read())!= -1,用读取到的字符(内容)和-1进行比较
         */
        while((ch=reader.read())!= -1){
    
    
            //ch = reader.read();
            System.out.println(ch);

        }


        //3.释放资源
        reader.close();
    }
}

创建字符流读数据-按字符数组读取

创建字符流读文件对象:
Reader reader = new FileReader("readme.txt");
调用方法读取数据:
char[] chs = new char[2048];
int len = r.read(chs);

读取字符到数组中,返回读取的字符数,若到达流的末尾,返回-1

异常处理
throws IOException
关闭资源:
reader.close();
package cn.itcast.demo22;
/*
  字符流读数据:
        Reader类中的方法:
        int read(char[] chs): 一次读一个字符数组,将读取到的内容存入到数组中
                             并返回读取到的有效字符流,读不到返回-1
        FileReader类的构造方法:
              Public FileReader(String pathname):根据传入的字符串形式的路径,获取字符输入流对象



 */

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

public class ReaderDemo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流读取数据,一次读取一个字符数据
        //1.创建字符输入流对象  2.txt里面只有abcdefg这个字符串
        Reader reader = new FileReader("lib/2.txt");

        //2.读取数据
        char[] chs = new char[3];//字符数组初始长度为3
        int len1 = reader.read(chs);
        System.out.println(chs);//a,b,c
        System.out.println(len1);//返回值为3


        int len2 = reader.read(chs);
        System.out.println(chs);//d,e,f
        System.out.println(len2);//返回值为3


        int len3 = reader.read(chs);
        System.out.println(chs);//g,e,f 最后只剩g所以返回值为1,但是要返回三个,那么前面的def只有d被g覆盖了,其余的不变,因为没有字母进行e和f的覆盖
        System.out.println(len3);//返回值为1

        int len4 = reader.read(chs);
        System.out.println(chs);//g,e,f
        System.out.println(len4);//返回值为-1

        //3.释放资源
        reader.close();
    }
}

package cn.itcast.demo22;
/*
  字符流读数据:
        Reader类中的方法:
        int read(char[] chs): 一次读一个字符数组,将读取到的内容存入到数组中
                             并返回读取到的有效字符流,读不到返回-1
        FileReader类的构造方法:
              Public FileReader(String pathname):根据传入的字符串形式的路径,获取字符输入流对象



 */

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

public class ReaderDemo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流读取数据,一次读取一个字符数据
        //1.创建字符输入流对象
        Reader reader = new FileReader("lib/2.txt");

        //2.读取数据
        /*char[] chs = new char[3];//字符数组初始长度为3
        int len1 = reader.read(chs);
        System.out.println(chs);//a,b,c
        System.out.println(len1);//返回值为3


        int len2 = reader.read(chs);
        System.out.println(chs);//d,e,f
        System.out.println(len2);//返回值为3


        int len3 = reader.read(chs);
        System.out.println(chs);//g,e,f
        System.out.println(len3);//返回值为1

        int len4 = reader.read(chs);
        System.out.println(chs);//g,e,f
        System.out.println(len4);//返回值为-1*/
        /*
        优化上述的代码,while循环
         */
        //定义字符数组
        char[] chs = new  char[3];
        //定义一个变量,记录读取到的有效字符数
        int len;
        while((len = reader.read(chs))!=-1){
    
    
            //将读取到的内容,转换成字符串,然后打印
            /*
             chs :表示要操作的数组
             0:表示起始索引
             len:表示要操作的字符个数
             */
            String s = new String(chs,0,len);//传字符数组、起始索引、长度
            System.out.println(s);

        }


        //3.释放资源
        reader.close();
    }
}

字符流写数据-按单个字符写入

创建字符流写文件对象:

Writer writer = new FileWriter("dest.txt");
调用方法写入数据
int x = '中';
writer.write(x);
写一个字符
异常处理
throws IOException
关闭资源
writer.close();
package cn.itcast.demo23;
/*
字符流写数据:
     Writer类中的方法:
             void write(int ch):  一次写一个字符
             void write(char[] chs,int index,int len):一次写一个指定的字符数组
             void write(String str):一次写一个字符串

     FileWriter 类的构造方法:
              public FileWriter(String pathname):根据传入的字符串形式的路径,获取字符输出流对象
 */

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

public class WriterDemo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流写数据
        //1.创建字符输出流对象
        Writer writer = new FileWriter("lib/1.txt");
        //2.写数据
        //一次写一个字符
        writer.write('好');//把原来1.txt文件里面的abc给覆盖了  abc被覆盖为好


        //3.释放资源
        writer.close();
    }
}

字符流写数据-按字符数组写入

创建字符流写文件对象:

Writer writer = new FileWriter("dest.txt");
调用方法写数据:
char[] chs = {
    
    '橙','心','橙','意'};
writer.write(chs);
写一个字符数组
异常处理:
throws IOException
关闭资源:
writer.close();
package cn.itcast.demo23;
/*
字符流写数据:
     Writer类中的方法:
             void write(int ch):  一次写一个字符
             void write(char[] chs,int index,int len):一次写一个指定的字符数组
             void write(String str):一次写一个字符串

     FileWriter 类的构造方法:
              public FileWriter(String pathname):根据传入的字符串形式的路径,获取字符输出流对象
 */

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

public class WriterDemo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流写数据
        //1.创建字符输出流对象
        Writer writer = new FileWriter("lib/1.txt");
        //2.写数据
        //一次写一个字符
       // writer.write('好');//把原来1.txt文件里面的abc给覆盖了  abc被覆盖为好

        //一次写一个指定的字符数组
        char[] chs = {
    
    '黑','马','程','序','员'};
        writer.write(chs,2,3);


        //3.释放资源
        writer.close();
    }
}

字符流写数据-按字符串写入

创建字符流写文件对象:

Writer writer = new FileWriter("dest.txt");
调用方法写入数据:
writer.write("小黑爱学习");
写入一个字符串
异常处理:
throws IOException
关闭资源:
writer.close();
package cn.itcast.demo23;
/*
字符流写数据:
     Writer类中的方法:
             void write(int ch):  一次写一个字符
             void write(char[] chs,int index,int len):一次写一个指定的字符数组
             void write(String str):一次写一个字符串

     FileWriter 类的构造方法:
              public FileWriter(String pathname):根据传入的字符串形式的路径,获取字符输出流对象
 */

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

public class WriterDemo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流写数据
        //1.创建字符输出流对象
        Writer writer = new FileWriter("lib/1.txt");
        //2.写数据
        //一次写一个字符
       // writer.write('好');//把原来1.txt文件里面的abc给覆盖了  abc被覆盖为好

        //一次写一个指定的字符数组
       /* char[] chs = {'黑','马','程','序','员'};
        writer.write(chs,2,3);*/

        //一次写一个字符串
        writer.write("好好学习,知识改变命运");



        //3.释放资源
        writer.close();
    }
}

字符流读写数据

字符流拷贝文件-按单个字符读写

创建字符流读文件对象:
Reader reader = new FileReader("readme.txt");
创建字符流写文件对象
Writer writer = new FileWriter("dest.txt");
调用方法读取数据
int data = reader.read();
调用方法写入数据
writer.write(data);
异常处理
throws IOException
关闭资源
reader.close();
writer.close();
package cn.itcast.demo24;

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

public class CopyFile1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流拷贝文件,一次读写一个字符
        //例如。将1.txt文件中的内容复制到2.txt文件中
        /*
        IO流拷贝文件核心六步:
            1.创建字符输入流对象,关联数据源文件
            2.创建字符输出流对象,关联目的地文件
            3.定义变量,记录读取的内容
            4.循环读取,只要条件满足就一直读,并将读取到的内容赋值给变量
            5.将读取到的数据写入到目的地文件中
            6.释放资源
         */
        //1.创建字符输入流对象,关联数据源文件
        //Reader reader = new FileReader("lib/1.txt");下面是这个代码的优化写法

        FileReader fr = new FileReader("lib/1.txt");
        //2.创建字符输出流对象,关联目的地文件
        FileWriter fw = new FileWriter("lib/3.txt");//细节:如果目的地文件不存在,程序会自动创建
        //3.定义变量,记录读取的内容
        int len;
        //4.循环读取,只要条件满足就一直读,并将读取到的内容赋值给变量
        while ((len = fr.read())!=-1){
    
    
            //5.将读取到的数据写入到目的地文件中
            fw.write(len);

        }

        //6.释放资源
        fr.close();
        fw.close();
    }
}

字符流拷贝文件-按字符数组读写

创建字符流读文件对象:
Reader reader = new FileReader("reader.txt");
创建字符流写文件对象:
Writer writer = new FileWriter("dest.txt");
调用方法读取数据:
char[] chs = new char[2048];//字符数组的长度最好定义为1024的整数倍, 计算机底层的换算单位是1024的整数倍
int len = reader.read(chs);
调用方法写数据:
writer.write(chs,0,len);
异常处理:
throws IOException
关闭资源
reader.close();
writer.close();
package cn.itcast.demo24;

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

public class CopyFile2 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //需求:通过字符流拷贝文件,一次读写一个字符数组
        //例如:将1.txt文件中的内容复制到2.txt文件中
        /*
        IO流核心六步:
                  1.创建字符流输入流对象,关联数据源文件
                  2.创建字符输出流对象,关联目的地文件
                  3.创建变量,用来记录读取到的有效字符数
                  4.通过循环进行读取,只要条件满足就一直读,并将读取到的有效数赋值给变量
                  5.将读取到的数据写入到目的地文件中
                  6.释放资源

         */
        //1.创建字符流输入流对象,关联数据源文件
        FileReader fr = new FileReader("lib/1.txt");
        //2.创建字符输出流对象,关联目的地文件
        FileWriter fw = new FileWriter("lib/2.txt");
        //3.创建变量,用来记录读取到的有效字符数
        char[] chs = new char[1024];
        //用来记录读取到的有效字符数
        int len;
        //4.通过循环进行读取,只要条件满足就一直读,并将读取到的有效数赋值给变量
        while ((len = fr.read(chs))!= -1){
    
    
            //5.将读取到的数据写入到目的地文件中
            fw.write(chs,0,len);

        }

        //6.释放资源
        fr.close();
        fw.close();
    }
}

猜你喜欢

转载自blog.csdn.net/doudoutj/article/details/113759318