文件操作File类和IO流

 

File 类

java.io包

File的对象创建:

public class TestFile1 {
    public static void main(String[] args) {
        File file1=new File("D:\\hello.txt");
        if(file1.exists()) {
            System.out.println("文件存在");
        }else {
            System.out.println("文件不存在");
        }
        File file2=new File("D:\\","test.txt");
        if(file2.exists()) {
            System.out.println("文件存在");
        }else {
            System.out.println("文件不存");
        }
        File file=new File("D:\\");
        File file3=new File(file,"test.txt");
        if(file3.exists()) {
            System.out.println("文件存在");
        }else {
            System.out.println("文件不存在");
        }
    }
}

File的createNewFile()方法: 当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件.

返回: 
如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false 

public class TestFie2 {
    public static void main(String[] args) throws IOException {
        File file=new File("D:\\test.txt");
        if(file.exists()) {
            System.out.println("文件存在");
        }else {
            //创建这个文件
            if(file.createNewFile()) {
                System.out.println("文件创建成功!");
            }
        }
    }
}

mkdir

public boolean mkdir() 创建此抽象路径名指定的目录。

public class TestFile3 {
    public static void main(String[] args) throws IOException {
        File path = new File("D:\\mydir");
        File myfile = new File(path, "test.txt");
        if (!path.exists()) {
            if (path.mkdir()) {
                if (!myfile.exists()) {
                    if (myfile.createNewFile()) {
                        System.out.println("文件创建成功!");
                    }
                }
            }
        }
    }
}

mkdirs

public boolean mkdirs() 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。注意,此操作失败时也可能已经成功地创建了一部分必需的父目录。

public class TestFile4 {
    public static void main(String[] args) throws IOException {
        File path=new File("D:\\newdir\\myfile");
        File file=new File(path,"test.txt");
        if(!path.exists()) {
            if(path.mkdirs()) {
                if(!file.exists()) {
                    if(file.createNewFile()) {
                        System.out.println("文件创建成功!");
                    }
                }
            }
        }
    }
}

delete

public boolean delete( 删除此抽象路径名表示的文件或目录。如果此路径名表示一个目录,则该目录必须为空才能删除。

public class TestFile5 {
    public static void main(String[] args) {
        File file=new File("D:\\newdir\\myfile\\test.txt");
        if(file.delete()) {
            System.out.println("删除成功!");
        }else {
            System.out.println("删除失败!");
        }
    }
}

getName

public String getName() 返回由此抽象路径名表示的文件或目录的名称。该名称是路径名名称序列中的最后一个名称。如果路径名名称序列为空,则返回空字符串。

getPath

public String getPath() 将此抽象路径名转换为一个路径名字符串。所得字符串使用默认名称分隔符分隔名称序列中的名称。

length

public long length() 返回由此抽象路径名表示的文件的长度。如果此路径名表示一个目录,则返回值是不确定的。

public class TestFile6 {
    public static void main(String[] args) {
        File file=new File("D:\\newdir\\myfile\\test.txt");
        String absolutePath=file.getAbsolutePath();
        System.out.println(absolutePath);

        String path=file.getPath();
        System.out.println(path);

        String name=file.getName();
        System.out.println(name);

        long length=file.length();
        System.out.println("文件的长度:"+length);
    }
}

lastModified

public long lastModified() 返回此抽象路径名表示的文件最后一次被修改的时间。

返回: 
表示文件最后一次被修改的时间的 long 值

public class TestFile7 {
    public static void main(String[] args) {
        File file=new File("D:\\newdir\\myfile\\test.txt");
        long lastModified=file.lastModified();
        Date date=new Date(lastModified);
        System.out.println(date.toLocaleString());
    }
}

isDirectory

public boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。

isFile

public boolean isFile() 测试此抽象路径名表示的文件是否是一个标准文件。

list

public String[] list() 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。

public class TestFile8 {
    public static void main(String[] args) {
        File file = new File("D:\\demo");
        //判断此file对象是否是一个目录
        if (file.isDirectory()) {
            String[] list = file.list();
            if (list != null) {
                for (int i = 0; i < list.length; i++) {
                    System.out.println(list[i]);
                }
            }
        }
    }
}

动态获取系统相关的分隔符

public class TestFile10 {
    public static void main(String[] args) {
        File file=new File("D:"+File.separator+"newdir"+
                File.separator+"myfile"+File.separator+"test.txt");
        if(file.exists()) {
            System.out.println("文件存在");
        }
    }
}

IO流

I指的是Input的首字母

O指的是Output的首字母

文件流中流动的是数据,从外部设备(磁盘文件,键盘,网络)流入程序的称为输入流,从程序流到外部设备的流称为输出流。

文件流按方向分可分为输入流和流出流。

文件流按流中流动的内容分为字节流和字符流。

InputStream此抽象类是表示字节输入流的所有类的超类。

OutputStream此抽象类是表示输出字节流的所有类的超类。

如果想要通过字节输出流,创建文件,并把程序数据输出到文件,需要使用OutputStream的子类。

FileOutputStream

public FileOutputStream(String name)
                 throws FileNotFoundException

创建一个向具有指定名称的文件中写入数据的输出文件流

public class OutputStreamTest1 {
    public static void main(String[] args) 
            throws IOException {
        OutputStream os=
                new FileOutputStream("D:"+File.separator+"abc.txt");
        String data="hello";
        os.write(data.getBytes());
        os.close();
        System.out.println("写文件已完成");
    }
}

FileOutputStream

public FileOutputStream(String name,
                        boolean append)
                 throws FileNotFoundException
参数: 
name - 与系统有关的文件名 
append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处 

这种构造方法,可以通过设置第二个参数,实现追加文件内容,而不是覆盖文件的内容的功能。

public class OutPutStreamTest2 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("D:\\a2.txt",true);
            fos.write("bbbbb".getBytes());
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null) {
                try {
                    fos.close();
                }catch(Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
以上示例实现向已存在文件a2.txt追加内容的功能。

从磁盘文件中读取数据到程序,需要用到文件输入流,如果要以字节流的方式读取数据,要用到InputStream,InputStream是一个抽象类,所以要想实现字节方式从文件中读数据,要用到InputStream的子类,FileInputStream。

InputStream:此抽象类是表示字节输入流的所有类的超类。
public class FileInputStream
    extends InputStream

FileInputStream 从文件系统中的某个文件中获得输入字节。哪些文件可用取决于主机环境。

public class InputStreamTest1 {
    public static void main(String[] args) throws IOException {
        InputStream is=new FileInputStream("D:\\abc.txt");
        //把流中的数据
        byte[] buffer=new byte[100];
        int length=is.read(buffer);
        if(length>0) {
            String s=new String(buffer);
            System.out.println(s);
        }
        is.close();
    }
}

使用FileInputStream实现文件的读取操作的标准写法

public class InputStreamTest2 {
    public static void main(String[] args) throws IOException {
        InputStream is=new FileInputStream("D:\\abc.txt");
        //把流中的数据
        byte[] buffer=new byte[1024];
        int len=-1;
        while((len=is.read(buffer))!=-1) {
            String s=new String(buffer,0,len);
            System.out.println(s);
        }
        is.close();
    }
}

练习:利用FileOutputStream和FileInputStream实现D:\abc.txt文件复制到C:\abc.txt

public class FileCopy1 {
    public static void main(String[] args) {
        // 从读取文件,到程序中,再把程序中读到的数据写到C磁盘根目录
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("D:\\a.png");
            byte[] buffer = new byte[1024];
            int len = -1;// 读取到的数据的实际长度
            fos = new FileOutputStream("D:\\b.png");
            while ((len = fis.read(buffer)) != -1) {
                // 把读到的数据再写到C:\\abc.txt
                fos.write(buffer, 0, len);
            }

        } catch (FileNotFoundException ex) {
            System.out.println("访问的文件不存在!");
        } catch (IOException ex) {
            System.out.println("文件的读取错误");
        } catch (Exception ex) {
            System.out.println("未知类型的错误");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }

        System.out.println("复制完成!");
    }
}

java.io

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

FileReader类的继承关系 FileReader-->InputStreamReader-->Reader

FileReader(String fileName) 
      在给定从中读取数据的文件名的情况下创建一个新 FileReader。
read()方法:
     public int read()
         throws IOException
读取单个字符
     public int read(char[] cbuf)
         throws IOException

将字符读入缓冲区数组中

public class FileRaderTest1 {
    public static void main(String[] args) throws IOException {
        FileReader fr=new FileReader("D:\\a2.txt");
        char[] cbuffer=new char[100];
        fr.read(cbuffer);
        String s=new String(cbuffer);
        System.out.println(s);
    }
}

如果文件的长度大于缓冲区的长度,那么需要进行循环读取,参考代码:

public class FileRaderTest1 {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("D:\\a2.txt");
        char[] cbuffer = new char[100];
        int len = -1;
        while ((len = fr.read(cbuffer)) != -1) {
            fr.read(cbuffer);
            String s = new String(cbuffer);
            System.out.println(s);
        }
        fr.close();
    }
}

java.io

类 Writer写入字符流的抽象类。

FileWriter这个类是Writer类的一个间接子类。

它和Writer之间的继承关系是: FileWriter->OuputStreamWriter->Writer

FileWriter构造方法:
FileWriter(String fileName) 
    根据给定的文件名构造一个 FileWriter 对象。
FileWriter(String fileName, boolean append) 
据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。

public class FileWriterTest1 {
    public static void main(String[] args) throws IOException {
        FileWriter writer=new FileWriter("D:\\a3.txt",true);
        String s="hello world!";
        char[] cbuf=s.toCharArray();
        writer.write(cbuf);
        //刷新缓冲区
        writer.flush();
        //关闭字符输出流
        writer.close();
    }
}

如果在使用构造方法时设置了append这个参数,则可以通过true实现向已有文件进行内容的追加,如果没有使用append则文件不存在就创建,存在就覆盖。

使用:FileReader和FileWriter实现文件的复制。

键盘输入6个学生的信息包括学生的姓名、语文、数学、英语 的考试成绩:
public class LianXi {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        FileWriter writer = null;
        try {
            writer = new FileWriter("D:\\student.txt");
            for (int i = 0; i < 3; i++) {
                System.out.println("请输入第"+(i+1)+"信息:");
                System.out.println("请输入姓名:");
                String name=input.next();
                System.out.println("请输入语文:");
                String chinese=input.next();
                System.out.println("请输入数学:");
                String math=input.next();
                System.out.println("请输入英语:");
                String english=input.next();

                writer.write(name+"\t"+chinese+"\t"+math+"\t"+english+"\r\n");
                writer.flush();
            }
        } catch (Exception ex) {
            throw new RuntimeException();
        }finally {
            if(writer!=null) {
                try {
                    writer.close();
                }catch(Exception ex) {
                    ex.printStackTrace();
                }finally {
                    writer=null;
                }
            }
        }
        System.out.println("保存完成!");
    }
}
posted @ 2019-08-12 21:39  流氓的夏天  阅读(519)  评论(0编辑  收藏  举报