关于File类、递归、IO流与字节流,作为程序员必须要知道的几点!!!

File类

概述

File类,文件和目录路径名的抽象表示形式。

构造方法

public File (String path);
public File (Strng parent ,String child);
public File (File parent,String child);
public class FileTestDemo {
    public static void main(String[] args) {
        //构造方法一
        File f1 = new File("D:\\Develop\\软件");
        //构造方法二
        File f2 = new File("D:\\Develop", "软件");
        //构造方法三
        File parent = new File("D:\\Develop");
        File f3 = new File(parent, "软件");
    }
}

常用方法

获取功能的方法

public String getAbsoiulePath()//绝对路径
public String getPath()//对象new的时候 传入的路径
public String getName()//获取文件和文件夹的名字
public long length()//获取文件的大小

注意:length只可以获取文件的大小,不可以获取文件夹的大小。

public class FileTestDemo2 {
    public static void main(String[] args){
        File ff=new File("D:\\Develop\\软件");
        //1、获取绝对路径
        String absolutePath = ff.getAbsolutePath();
        //2、对象new的时候 传入的路径
        String path = ff.getPath();
        //3、文件的名字
        String name = ff.getName();
        System.out.println(name);
        //4、获取文件的字节大小,单位是字节【如果是文件夹,则无法获取】
        long length = ff.length();
        System.out.println(length+"字节");
    }
}

绝对路径与相对路径【重点】

绝对路径:是指以盘符开头的路径。
相对路径:以当前项目的根目录为起始的路径。

判断功能的方法

public boolean exists()//判断是否存在
public boolean isDirectory()//判断File对象是否是文件夹
public boolean isFile()//判断File对象是否是文件

创建删除功能的方法

1、创建文件夹

public boolean mkdir();

2、创建文件

public boolean createNewFile();

3、创建多级文件夹

public boolean mkdirs()

4、删除方法

public boolean delete()
public class FileTestDemo5 {
    public static void main(String[] args) throws IOException {
        File ff = new File("2.txt");
        //创建文件
        boolean newFile = ff.createNewFile();
        System.out.println(newFile);
        ////创建文件夹
        boolean mkdir = ff.mkdir();
        System.out.println(mkdir);
        //创建多级文件夹
        File ff2 = new File("aa\\bb\\cc\\dd");
        boolean mkdirs = ff2.mkdirs();
        System.out.println(mkdirs);
        //删除文件夹
        boolean delete = ff2.delete();
        System.out.println(delete);
    }
}

注意:删除时只能删除对象代表的文件或者【空文件夹

目录的遍历

1、public String [] list();//列出当前文件下所有直接的文件和文件夹的名字
2、public File[] listFiles();//列出当前文件夹下所有的直接的文件和文件夹的File对象

public class FileTestDemo6 {
    public static void main(String[] args) {
        //必须是文件夹
        File ff = new File("D:\\Develop\\软件");
        String[] list = ff.list();
        for (String s : list) {
            System.out.println(s);
        }
        File[] files = ff.listFiles();
        for (File file : files) {
            System.out.println(file);
        }
    }
}

注意:list和listFiles只能列直接的子文件或子文件夹。

递归

概述

在方法中调用该方法本身(自己调自己)
StackOverflowError:无限递归(死递归),栈溢出错误。所以,如果要使用递归,必须要有出口!!!

    public static void main(String[] args) {
        mehtod1(10);
    }

    public static void mehtod1(int n) {
        if (n == 0) {
            return;//结束这个方法,即递归的出口
        }
        System.out.println("jkl"+n);
        mehtod1(n - 1);
    }

    public static void mehtod() {
        System.out.println("jkl");
        //此处是死递归
        mehtod();
    }
}

注意:就算有出口,还要保证递归在运行到出口前次数不能太多。

递归累和

案例计算1~n的和

//使用递归的三大步骤
//1、先定义一个方法
//2、找规律,调用自己
//3、让递归有结束条件
public class demo2 {
    public static void main(String[] args) {
        int getsum = getsum(10);
        System.out.println(getsum);
    }

    private static int getsum(int n) {
        if (n == 1) {
            return 1;

        }
        return getsum(n - 1) + n;

    }
}

递归求阶乘

    public static void main(String[] args) {
        int ji = getJi(4);
        System.out.println(ji);
    }

    private static int getJi(int n) {
        if (n == 1) {
            return 1;
        }
        return getJi(n-1)*n;
    }
}

案例练习:

//使用递归,计算斐波拉契数列的第n项的值. 斐波拉契数列是:1、1、2、3、5、8、13、21、34……
//其中,从第三项起,每一项都是前两项的和。
public class demo01 {
    public static void main(String[] args) {
        int i = diGui(5);//n代表传入的第几项
        System.out.println("第五项的值是:" + i);
    }

    private static int diGui(int n) {
        if (n == 1 || n == 2) {
            return 1;//递归出口
        } else {

        }

        return diGui(n - 1) + diGui(n - 2);
    }
}

文件搜索

在某个目录中找出所有的.txt文件

    public static void main(String[] args) {
        File ff = new File("D:\\Develop\\WorkSpace");
        find(ff);
    }

    private static void find(File file) {
        //列出该文件下所有的file对象
        File[] files = file.listFiles();
        //遍历数组
        for (File file1 : files) {
            //判断是否值.txt
            if (file1.getName().endsWith(".txt") && file1.isFile()) {
                System.out.println(file1);
            } else if (file1.isDirectory()) {//如果是文件夹
                find(file1);//递归
            }
        }
    }
}

IO流

概述

I:Input 输入流,数据从外部设备到程序中的,进行数据的读取。【读流】
o:Output 输出流,从程序到外部设备。【写流】
流:数据传输的过程比喻是流

IO流的分类

1、根据流的方向分为输入流和输出流
2、根据流中的数据类型,分为字节流和字符流
综合为:字节输入流、字节输出流和字符输入流、字符输出流

java中的四大流

字节输入流:InputStream(顶层父类,抽象类)
字节输出流:OutputStream((顶层父类,抽象类)
字符输入流:Reader(顶层父类,抽象类)
字符输出流:Writer((顶层父类,抽象类)

java中所有的流都会是以上四类中的某一个类,而且命名是有规范的!!!
规定为:功能名+父类名

字节流

万物皆对象和IO流一切皆字节

我们电脑所有的数据,最终都是由字节组成的

字节输出流

顶层父类:OutputStream(抽象类)
共性方法:

public void close();//关闭此流,释放资源
public void flush();//刷新缓冲区

public void write(byte b);//一次写一个字节  
public void write(byte[] bs);//一次写一个字节数组
public void write(byte[] bs,int startIndex,int len);//一个写一个字节数组的一部分

FileOutputStream类的使用

文件的字节输出流(向文件中写数据)
构造方法:

public FileOutputStream(String path)//必须传入文件的路径
public FileOutputStream(File file)//必须传入文件的File对象

代码实现:

    public static void main(String[] args) throws IOException {
        //创建一个 FileOutputStream
        FileOutputStream ff = new FileOutputStream("1.txt");
        //向文件中写数据
        //1、写一个字节
        ff.write(97);
        ff.write(55);
        //2、写一个字节数组
        byte[] bytes = {97,98,99};
        ff.write(bytes);
        byte[] bytes1 = "Hello".getBytes();
        ff.write(bytes1);
        //写一个字节数组的一部分
        byte[] byte3 = {97,98,99};
        ff.write(bytes,1,2);
    }
}

续写

public FileOutputStream(String path,boolean append)//必须传入文件的路径,append表示是否追加
public FileOutputStream(File file,boolean append)//必须传入文件的File对象
    public static void main(String[] args) throws IOException {
        //创建一个 FileOutputStream,表示不清空,继续追加
        FileOutputStream ff = new FileOutputStream("1.txt",true);
        //向文件中写数据
        //1、写一个字节
        ff.write(97);
    }
}

换行

只要向文件中写一个代表换行的符号即可;
windows:\r\n

    public static void main(String[] args) throws IOException {
        //创建一个 FileOutputStream
        FileOutputStream ff = new FileOutputStream("1.txt");
        for (int i = 0; i < 10; i++) {
            byte[] bytes = "java".getBytes();
            ff.write(bytes);
            //换行
            ff.write("\r\n".getBytes());

        }
    }
}

字节输入流

顶层父类:InputStream(抽象类)
共性方法:

public void close();//关闭此流,释放资源

public byte read();//一次读一个字节  
public int read(byte[] bs);//一次读取一个字节数组,返回值表示实际读取额字节个数

FileInputStream类的使用

文件的字节输入流:从文件中读取以字节为单位的数据
构造方法:

public FileInputStream(String path)//必须传入文件的路径
publicFileInputStream(File file)//必须传入文件的File对象

读取一个字节

代码实现:

    public static void main(String[] args) throws Exception {
        FileInputStream ff = new FileInputStream("1.txt");
        /*以上构造方法的三个事情
        1、创建了一个对象
        2、判断文件是否存在,如果不存在,会抛出异常【系统找不到文件】;如果存在,不清空文件
        3、让对象和文件绑定
        * */
        //一次读取文件中的一个字节
        int read = ff.read();
        System.out.println((char) read);//转换成Char,结果为【H】
        //一次读取一个字节的标准循环的代码
        //先读,赋给b,判断!=-1
        int b = 0;//保存读取到的字节
        while ((b = ff.read()) != -1) {
            System.out.println((char) read);
        }
    }
}

读取一个字节数组

代码实现:

    public static void main(String[] args) throws IOException {
        //创建一个 FileOutputStream
        FileOutputStream ff = new FileOutputStream("1.txt");
        //向文件中写数据
        //1、写一个字节
        ff.write(97);
        ff.write(55);
        //2、写一个字节数组
        byte[] bytes = {97,98,99};
        ff.write(bytes);
        byte[] bytes1 = "Hello".getBytes();
        ff.write(bytes1);
        //写一个字节数组的一部分
        byte[] byte3 = {97,98,99};
        ff.write(byte3,1,2);
    }
}

复制

代码实现:

public class Copy {
    public static void main(String[] args) throws IOException {
        //复制文件
        //1、源文件
        FileInputStream ff = new FileInputStream("D:\\Develop\\WorkSpace\\it\\1.txt");
        //2、目标文件
        FileOutputStream ff2 = new FileOutputStream("D:\\Develop\\WorkSpace\\copy.txt");
        //3、复制文件
        byte[] bs = new byte[1024];
        int len = 0;
        while ((len = ff.read(bs)) != -1) {
            ff2.write(bs, 0, len);//为了防止最后一次读取时写入多余的数据
        }
        ff2.close();//先开后放
        ff.close();
    }
}

案例练习

需求:从控制台循环接收用户录入的学生信息,输入格式为:学号-学生名字,将学生信息保存到F盘下面的stu.txt文件中,一个学生信息占据一行数据。当用户输入end时停止输入。

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学生信息,输入格式为:学号-学生名字");
        FileOutputStream ff = new FileOutputStream("D:\\stu.txt");
        //3. 编写一个死循环,接收控制台录入的学生信息
        while (true) {
            String students = scanner.nextLine();
            if (students.contains("end")) {
                break;
            } else {
                byte[] bytes = students.getBytes();
                ff.write(bytes);
                //换行
                ff.write("\r\n".getBytes());
            }

        }
				ff.close();//关闭流
    }
}

小结

现在的努力都是为了以后可以更好,坚持下去就是胜利!!!

发布了34 篇原创文章 · 获赞 9 · 访问量 1284

猜你喜欢

转载自blog.csdn.net/weixin_43616750/article/details/104981974