FIle

FIle 是文件对象,可以表示一个文件,也可以表示文件夹。研究其源码,没有什么意义,我们要做的,是研究怎么用。

常用的文件操作

方式一:根据路径创建一个文件(只能创建在磁盘根目录)
    @Test
    public void createFile(){
        String filePath="d:\\file.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println(file.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
方式二:根据父目录文件+子路径构建文件
    @Test
    public void createFile1(){
        File parentFile = new File("D:\\");
        String fileName = "file2.txt";
        File file1 = new File(file, s);

        try {
            file1.createNewFile();
            System.out.println("done!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
方式三:根据父目录+子路径构建
    @Test
    public void createFile2(){
        String parentPath = "d:\\";
        String fileName = "file3.txt";
        File file = new File(parentPath, filePath);

        try {
            file.createNewFile();
            System.out.println("文件3创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

目录的操作

Java传统的IO API种使用java.io.File类中的file.mkdir()和file.mkdirs()方法创建文件夹
file.mkdir()创建文件夹成功返回true,失败返回false。如果被创建文件夹的父文件夹不存在也返回false.没有异常抛出。
file.mkdirs()创建文件夹连同该文件夹的父文件夹,如果创建成功返回true,创建失败返回false。创建失败同样没有异常抛出。
创建文件,测试mkdir,创建文件夹不包含父文件夹

@Test
    public void createDir1(){
        String dirName = "d:\\data\\test";
        File directory = new File(dirName);
        try {
            boolean hasSucceeded = directory.mkdir();
            System.out.println("创建文件夹结果(不含父文件夹):" + hasSucceeded);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void createDir2(){
        String dirName = "d:\\data1\\test";
        File directory = new File(dirName);
        try {
            boolean hasSucceeded = directory.mkdirs();
            System.out.println("创建文件夹结果(包含父文件夹):" + hasSucceeded);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Test
    public void deleteFile(){
        File file = new File("D:\\data\\text.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(file.delete()){
            System.out.println("empty");

        }else {
            System.out.println(file.getName());
        }
    }

获取文件的信息

  @Test
    public void info(){
        /**
         * 创建文件
         */
        File file = new File("D:\\data\\file.txt");

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 调用方法得到文件信息
         */
        System.out.println("文件名称"+file.getName());
        System.out.println("文件绝对路径"+file.getAbsolutePath());
        System.out.println("文件父目录"+file.getParent());
        System.out.println("文件大小(字节)"+file.length());
        System.out.println("文件是否存在"+file.exists());
        System.out.println("是否是文件"+file.isFile());
        System.out.println("是否是目录"+file.isDirectory());


    }

IO简介

流 Stream

在学习IO流之前,我们首先需要学习的概念就是Stream流
为了方便理解,我们可以把数据的读写操作抽象成数据在”管道”中流动,但需注意:
1.流只能单方向流动
2.输入流用来读取 → in
3.输出流用来写出 → out
4.数据只能从头到尾顺序的读写一次
所以以程序的角度来思考,In/out 相对于程序而言的输入(读取)/输出(写出)的过程.

IO流的继承结构

在java中,根据处理的数据单位不同,可以把流分为字节流和字符流
字节流 : 针对二进制文件
字符流 : 针对文本文件

IO流的分类:

按照流的方向:输入流和输出流
按照流的数据类型:字节流和字符流
下面介绍一下字节流和字符流的顶级父类
字节流:

输入流:InputStream
输出流:OutputStream

字符流:

输入流:Reader
输出流:Writer

—字节流读取—

字节流是由字节组成的,字符流是由字符组成的。
Java里字符由两个字节组成.字节流是基本流,主要用在处理二进制数据。
所以字节流是比较常用的,可以可以处理多种不同种类的文件,比如文本文档/音频/视频等等

InputStream抽象类

此抽象类是表示字节输入流的所有类的超类/抽象类,不可创建对象哦

FileInputStream子类

直接插在文件上,直接读取文件数据

BufferedInputStream子类

BufferedInputStream 为另一个输入流添加一些功能,在创建BufferedInputStream 时,会创建一个内部缓冲区数组(默认8k大小)。在读取或跳过流中的字节时,可根据需要从包含的输入流再次填充该内部缓冲区,一次填充多个字节。

import java.io.*;

public class TestIn {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\ready\\1.txt");
        if (!file.exists()){
            file.createNewFile();
        }else {
            System.out.println("file already exist");
            //method();
            method2();
        }


    }
    //本方法用于测试高效字节流的读取
    private static void method2() {
        //定义一个在本方法中都生效的局部变量in,注意手动初始化,值为null
        InputStream in = null;
        try {
            //1.创建高效字节输入流对象
//            InputStream in = new BufferedInputStream(
//                    new FileInputStream(new File("E:\\ready\\1.txt")));
            in = new BufferedInputStream
                    (new FileInputStream("E:\\ready\\1.txt"));
            //2.使用流进行读取
            int b;
            while ((b= in.read())!= -1){
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {//关流操作写在finally{}中
            //3.流用完以后一定要关闭!!!
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    //本方法用于测试字节流的读取
    private static void method() {
        //创建一个在本方法都生效的局部变量注意手动初始化
        InputStream in = null;
        try {
            //1.创建字节输入流对象用于读取
            // InputStream in = new InputStream();//报错原因:抽象类不可实例化
            //InputStream in = new FileInputStream(new File("E:\\ready\\1.txt"));
            in = new FileInputStream("E:\\ready\\1.txt");
            //2.开始读取
            /*read()每次调用都会读取一个字节,如果读到了数据的末尾,返回-1*/
//            System.out.println(in.read());
//            System.out.println(in.read());
//            System.out.println(in.read());
//            System.out.println(in.read());
            //需求:需要循环读取文件中的所有内容,直至读完
            //定义变量,记录读到的数据
            int b;
            while ((b = in.read()) != -1) {
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();//打印错误信息
            /*try-catch结构中的第三个部分:finally{}
             * 这部分不论是否捕获到异常,是一定会被执行到的代码,常用于关流*/
        } finally {
            try {
                //3.释放资源,流资源用完必须释放!!!
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

—字符流读取—

常用于处理纯文本数据,读写容易出现乱码的现象,在读写时,最好指定编码集为UTF-8

Reader抽象类

用于读取字符流的抽象类。

FileReader子类

用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。要自己指定这些值,可以先在 FileInputStream 上构造一个 InputStreamReader。

BufferedReader子类

从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。

import java.io.*;

/*本类用于测试字符流的读取*/
public class TestIn2 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\ready\\1.txt");
        if (!file.exists()){
            file.createNewFile();
        }else {
            System.out.println("file already exist");
            //method();//测试普通字符输入流
            method2();//测试高效字符输入流
        }

    }
    //创建一个用于测试高效字符输入流的方法
    private static void method2() {
        //1.定义一个在本方法都生效的局部变量,手动初始化值null
        Reader in=null;
        try{
            //1.创建高效字符读取流对象
            //in = new BufferedReader(new FileReader(new File("E:\\ready\\1.txt")));
            in = new BufferedReader(new FileReader("E:\\ready\\1.txt"));
            //2.使用流对象
            int b;
            while((b=in.read())!=-1){
                System.out.println(b+"="+(char)b);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //3.关闭流对象
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //创建一个用于测试普通字符输入流的方法
    private static void method() {
        //1.1创建一个在本方法中都生效的局部变量,注意初始化值null
        Reader in = null;
        try {
            //1.2创建字符输入流对象,注意需要捕获异常
            //Reader in = new Reader();//报错原因:抽象父级不可实例化
            //in = new FileReader(new File("E:\\ready\\1.txt"));
            in = new FileReader("E:\\ready\\1.txt");
            //2.使用流对象
            //System.out.println(in.read());
            //需求:循环读取文件中的所有内容,只要不是-1,就说明还有数据,继续读取
            //3.1定义变量,记录读取到的数据
            int b;
            while((b = in.read())!= -1){
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//3.关流
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

—字节流写出—

OutputStream抽象类

此抽象类是表示输出字节流的所有类的超类.输出流接受输出字节并将这些字节发送到某个接收器.

FileOutputStream 子类

直接插在文件上,直接写出文件数据

BufferedOutputstream 子类

该类实现缓冲的输出流,通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必每次针对字节写出调用底层系统

import java.io.*;

/*本类用于测试字节输出流*/
public class TestOut {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\ready\\2.txt");
        if (!file.exists()){
            file.createNewFile();
        }else {
            System.out.println("file already exist");
            method();//用于测试普通字节输出流
            //method2();//用于测试高效字节输出流
        }

    }
    //创建一个用于测试高效字节输出流的方法
    private static void method2() {
        //1.创建一个在本方法都生效的局部变量,注意手动初始化
        OutputStream out = null;
        try{
            //2.创建高效字节输出流对象
//          out = new BufferedOutputStream(new FileOutputStream(new File("E:\\ready\\2.txt")));
            out = new BufferedOutputStream(new FileOutputStream("E:\\ready\\2.txt"));
            //3.使用流对象--进行写出操作
            out.write(97);//对应ASCII码表中的a
            out.write(98);//对应ASCII码表中的b
            out.write(99);//对应ASCII码表中的c
        }catch (Exception e){
            e.printStackTrace();
        }finally {//关流操作要放在finally{}中
            try {
                //4.关流
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //创建一个用于测试普通字节输出流的方法
    private static void method() {
        //1.创建一个在本方法中都生效的局部变量,注意手动初始化null
        OutputStream out = null;
        //2.创建try-catch-finally结构,因为IO操作可能会产生异常
        try{
            //3.创建普通字节输出流对象
            //out = new FileOutputStream(new File("E:\\ready\\2.txt"));
            //out = new FileOutputStream("E:\\ready\\2.txt");
            out = new FileOutputStream("E:\\ready\\2.txt",true);
            //4.使用流对象--进行写出操作
            out.write(97);//对应ASCII码表中的a
            out.write(98);//对应ASCII码表中的b
            out.write(99);//对应ASCII码表中的c
        }catch (Exception e){
            e.printStackTrace();
        }finally {//如果想要代码一定会执行,需要写在finally中
            try {
                //5.关流操作
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

—字符流写出—

Writer 抽象类

写入字符流的抽象类

FileWriter 子类

用来写入字符文件的便捷类,此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的.如果需要自己自定义这些值,可以先在FileOutputStream上构造一个OutputStreamWriter.

BufferedWriter子类

将文本写入字符输出流,缓冲各个字符,从而提供单个字符,数组和字符串的高效写入.可以指定缓冲区的大小,或者接受默认的大小,在大多数情况下,默认值就足够大了

import java.io.*;

/*本类用于测试字符输出流*/
public class TestOut2 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\ready\\2.txt");
        if (!file.exists()){
            file.createNewFile();
        }else {
            System.out.println("file already exist");
            //method();//用于测试普通字符输出流
            method2();//用于测试高效字符输出流
        }

    }
    //创建一个用于测试高效字符输出流的方法
    private static void method2() {
        //1.创建一个在本方法都生效的局部变量,值为null,注意手动初始化!!!
        Writer out = null;
        //2.由于程序可能会抛出异常,所以需要写一个try-catch-finally结构
        try{//存放可能会抛出异常的代码
            //3.创建普通字符输出流对象
            //out = new BufferedWriter(new FileWriter(new File("E:\\ready\\2.txt")));
            //out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt"));
            out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt",true));
            //4.使用流对象
            out.write(100);
            out.write(100);
            out.write(100);
            out.write(100);
            out.write(100);
        }catch (Exception e){//匹配并捕获异常
            e.printStackTrace();//如果捕获到异常就打印错误信息
        }finally {//一定会被执行到的代码块,常用于关流
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //创建一个用于测试普通字符输出流的方法
    private static void method() {
        //1.创建一个在本方法都生效的局部变量,值为null,注意手动初始化!!!
        Writer out = null;
        //2.由于程序可能会抛出异常,所以需要写一个try-catch-finally结构
        try{//存放可能会抛出异常的代码
            //3.创建普通字符输出流对象
            //out = new FileWriter(new File("E:\\ready\\2.txt"));
            //out = new FileWriter("E:\\ready\\2.txt");
            out = new FileWriter("E:\\ready\\2.txt",true);
            //4.使用流对象
            out.write(98);
            out.write(98);
            out.write(98);
            out.write(98);
        }catch (Exception e){//匹配并捕获异常
            e.printStackTrace();//如果捕获到异常就打印错误信息
        }finally {//一定会被执行到的代码块,常用于关流
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

复制粘贴文本

import java.io.*;
import java.util.Scanner;

/*本类用于练习文件复制综合案例*/
public class TestCopyFile {
    public static void main(String[] args) {
        //1.提示并接收用户输入的两个路径
        System.out.println("请输入源文件路径");//--被复制的那个文件
        String f = new Scanner(System.in).nextLine();
        System.out.println("请输入新文件路径:");//--复制好的新文件
        String t = new Scanner(System.in).nextLine();

        //2.调用创建好的自定义方法完成文件复制
        //ZFCopy(f,t);//用字符流完成文件的复制案例
        ZJCopy(f,t);//用字节流完成文件的复制案例
    }
    //利用字节流完成文件复制案例
    private static void ZJCopy(String f, String t) {
        //1.定义在整个方法都生效的局部变量,注意手动初始化,引用类型默认值为null
        InputStream in = null;
        OutputStream out = null;
        //2.由于代码可能会发生异常,所以需要编写try-catch-finally结构
        try{
            //3.1创建高效字节输入流对象--FIS的参数是用户传入的源文件路径f
            in = new BufferedInputStream(new FileInputStream(f));
            //3.2创建高效字节输出流对象--FOS的参数是用户传入的新文件路径t
            out = new BufferedOutputStream(new FileOutputStream(t));

            //4.利用创建好的流对象完成业务
            //4.1定义变量用来保存读到的数据
            int b;
            //4.2循环读取源文件中的数据,只要不是-1,说明还有数据循环继续
            while((b = in.read()) != -1){
                //4.3将读到的数据写入到新文件中
                out.write(b);
            }
            System.out.println("恭喜您!文件复制成功!");
        }catch (Exception e){
            System.out.println("很抱歉!文件复制失败!");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //利用字符流完成文件复制案例
    private static void ZFCopy(String f, String t) {
        //1.定义在整个方法中都生效的局部变量,注意手动初始化,默认值为null
        Reader in = null;
        Writer out = null;
        //2.由于代码可能会发生异常,所以需要编写try-catch-finally结构
        try{
            //3.1创建高效字符输入流对象
            in = new BufferedReader(new FileReader(f));
            //3.2创建高效字符输出流对象
            out = new BufferedWriter(new FileWriter(t));

            //4.拿到流对象以后,就可以使用流对象来完成业务了
            //4.1定义变量用来保存读到的数据
            int b;
            //4.2循环读取源文件,直到返回值为-1,说明没有数据了,再结束循环
            while ((b=in.read())!=-1) {
                //4.3将本轮循环中读到的数据写入到新文件中
                out.write(b);
            }
            System.out.println("恭喜您!文件复制成功!");
        }catch (Exception e){
            System.out.println("很抱歉!文件复制失败!");
            e.printStackTrace();
        }finally {
            /*关流是有顺序的:如果有多个流,最后创建的流最先关闭
             * 多条关流语句需要各自try-catch*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

原文地址:http://www.cnblogs.com/foxcyg/p/16855699.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性