文件与流

什么是文件?

文件可认为是相关记录或放在一起的数据的集合

文件一般存储在哪里?

image

JAVA程序如何访问文件属性?

java.io.File 类

File类访问文件属性

image

JAVA中的文件及目录处理类

在Java中提供了操作文件及目录(即我们所说的文件夹)类File。有以下几点注意事项:

(1)不论是文件还是目录都使用File类操作;

(2)File类只提供操作文件及目录的方法,并不能访问文件的内容,所以他描述的是文件本身的属性;

(3)如果要访问文件本身,用到了我们下面要学习的IO流.

一:构造方法

File 文件名/目录名 = new File("文字路径字符串");

在Java中提供了几种创建文件及目录的构造方法,但大体上都是用参数中的文字路径字符串来创建。

二:一般方法

(1)文件检测相关方法

boolean isDirectory():判断File对象是不是目录

boolean isFile():判断File对象是不是文件

boolean exists():判断File对象对应的文件或目录是不是存在

(2)文件操作的相关方法

boolean createNewFile():路径名指定的文件不存在时,创建一个新的空文件

boolean delete():删除File对象对应的文件或目录

(3)目录操作的相关方法

boolean mkdir():单层创建空文件夹

boolean mkdirs():多层创建文件夹

File[] listFiles():返回File对象表示的路径下的所有文件对象数组

(4)访问文件相关方法

String getName():获得文件或目录的名字

String getAbsolutePath():获得文件目录的绝对路径

String getParent():获得对象对应的目录的父级目录

long lastModified():获得文件或目录的最后修改时间

long length() :获得文件内容的长度

目录的创建

public class MyFile {
  public static void main(String[] args) {
      //创建一个目录
      File file1 = new File("d:\\test");
      //判断对象是不是目录
      System.out.println("是目录吗?"+file1.isDirectory());
      //判断对象是不是文件
      System.out.println("是文件吗?"+file1.isFile());
      //获得目录名
      System.out.println("名称:"+file1.getName());
      //获得相对路径
      System.out.println("相对路径:"+file1.getPath());
      //获得绝对路径
      System.out.println("绝对路径:"+file1.getAbsolutePath());
      //最后修改时间
      System.out.println("修改时间:"+file1.lastModified());
      //文件大小
      System.out.println("文件大小:"+file1.length());
  }
}

程序首次运行结果:

是目录吗?false
是文件吗?false
名称:test
相对路径:d:\test
绝对路径:d:\test
修改时间:0
文件大小:0

file1对象是目录啊,怎么在判断“是不是目录”时输出了false呢?这是因为只是创建了代表他是目录的对象,还没有真正的创建,这时候要用到mkdirs()方法,如下:

public class MyFile {
    public static void main(String[] args) {
        //创建一个目录
        File file1 = new File("d:\\test\\test");
        file1.mkdirs();//创建了多级目录
        //判断对象是不是目录
        System.out.println("是目录吗?"+file1.isDirectory());     
    }
}

文件的创建

public class MyFile {
    public static void main(String[] args) {
        //创建一个文件
        File file1 = new File("d:\\a.txt");

        //判断对象是不是文件
        System.out.println("是文件吗?"+file1.isFile());  
    }
}

首次运行结果:

是文件吗?false

同样会发现类似于上面的问题,这是因为只是代表了一个文件对象,并没有真正的创建,要用到createNewFile()方法,如下

public class MyFile {
    public static void main(String[] args) {
        //创建一个文件对象
        File file1 = new File("d:\\a.txt");
        try {
            file1.createNewFile();//创建真正的文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断对象是不是文件
        System.out.println("是文件吗?"+file1.isFile());  
    }
}

文件夹与文件的创建目录

文件时存放在文件夹下的,所以应该先创建文件夹,后创建文件,如下:

public class MyFile {
    public static void main(String[] args) {
        //代表一个文件夹对象,单层的创建
        File f3 = new File("d:/test");
        File f4 = new File("d:/test/a.txt");
        f3.mkdir();//先创建文件夹,才能在文件夹下创建文件
        try {
            f4.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //代表一个文件夹对象,多层的创建
        File f5= new File("d:/test/test/test");
        File f6 = new File("d:/test/test/test/a.txt");
        f5.mkdirs();//多层创建
        try {
            f6.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果为,在D磁盘的test文件夹下有一个a.txt,在D磁盘的test/test/test下有一个a.txt文件。

编程:判断是不是有这个文件,若有则删除,没有则创建

public class TestFileCreatAndDele {
    public static void main(String[] args) {
        File f1 = new File("d:/a.txt");
        if(f1.exists()){//文件在吗
            f1.delete();//在就删除
        }else{//不在
            try {
                f1.createNewFile();//就重新创建
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件的逐层读取

File的listFiles()只能列出当前文件夹下的文件及目录,那么其子目录下的文件及目录该如何获取呢?解决的办法有很多,在这运用递归解决.

//逐层获取文件及目录
public class TestFindFile {
    public static void openAll(File f) {// 递归的实现
        File[] arr = f.listFiles();// 先列出当前文件夹下的文件及目录
        for (File ff : arr) {
            if (ff.isDirectory()) {// 列出的东西是目录吗
                System.out.println(ff.getName());
                openAll(ff);// 是就继续获得子文件夹,执行操作
            } else {
                // 不是就把文件名输出
                System.out.println(ff.getName());
            }
        }
    }
    public static void main(String[] args) {
        File file = new File("d:/test");// 创建目录对象
        openAll(file);// 打开目录下的所有文件及文件夹
    }
}

如何读写文件?
通过流来读写文件
流是指一连串流动的字符,是以先进先出方式发送信息的通道

image

输入/输出流与数据源

image

Java流的分类

image

文本文件的读写

  • 用FileInputStream和FileOutputStream读写文本文件
  • 用BufferedReader和BufferedWriter读写文本文件

二进制文件的读写

  • 使用DataInputStream和DataOutputStream读写二进制文件

使用FileInputStream 读文本文件

image

InputStream类常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
子类FileInputStream常用的构造方法
FileInputStream(File file)
FileInputStream(String name)

一个一个字节的读

 public static void main(String[] args) throws IOException {
    // write your code here
        File file = new File("d:/我的青春谁做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[100];//保存从磁盘读到的字节
        int index = 0;

        int content = fileInputStream.read();//读文件中的一个字节

        while (content != -1)//文件中还有内容,没有读完
        {
            buffer[index] = (byte)content;
            index++;

            //读文件中的下一个字节
            content = fileInputStream.read();
        }

        //此时buffer数组中读到了文件的所有字节

        String string = new String(buffer,0, index);

        System.out.println(string);

    }

一批一批的读

  public static void main(String[] args) throws IOException {
        // write your code here

        File file = new File("d:/我的青春谁做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[SIZE];//保存从磁盘读到的字节

        int len = fileInputStream.read(buffer);//第一次读文件中的100个字节
        while (len != -1)
        {
            String string = new String(buffer,0, len);
            System.out.println(string);
            //读下一批字节
            len = fileInputStream.read(buffer);
        }
    }

使用FileOutputStream 写文本文件

image
public class FileOutputStreamTest {

    public static void main(String[] args) {
        FileOutputStream fos=null;
         try {
             String str ="好好学习Java";
             byte[] words  = str.getBytes();
             fos = new FileOutputStream("D:\\myDoc\\hello.txt");
             fos.write(words, 0, words.length);
             System.out.println("hello文件已更新!");
          }catch (IOException obj) {
              System.out.println("创建文件时出错!");
          }finally{
              try{
                  if(fos!=null)
                      fos.close();
              }catch (IOException e) {
                 e.printStackTrace();
              }
          }
    }
}

OutputStream类常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子类FileOutputStream常用的构造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
1、前两种构造方法在向文件写数据时将覆盖文件中原有的内容
2、创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件

复制文件内容

文件“我的青春谁做主.txt”位于D盘根目录下,要求将此文件的内容复制到
C:\myFile\my Prime.txt中
实现思路

  1. 创建文件“D:\我的青春谁做主.txt”并自行输入内容
  2. 创建C:\myFile的目录。
  3. 创建输入流FileInputStream对象,负责对D:\我的青春谁做主.txt文件的读取。
  4. 创建输出流FileOutputStream对象,负责将文件内容写入到C:\myFile\my Prime.txt中。
  5. 创建中转站数组words,存放每次读取的内容。
  6. 通过循环实现文件读写。
  7. 关闭输入流、输出流
  public static void main(String[] args) throws IOException {
        //创建E:\myFile的目录。

        File folder = new File("E:\\myFile");
        if (!folder.exists())//判断目录是否存在
        {
            folder.mkdirs();//如果不存在,创建该目录
        }

        //创建输入流
        File fileInput = new File("d:/b.rar");
        FileInputStream fileInputStream = new FileInputStream(fileInput);
        //创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\myFile\\c.rar");
        //创建中转站数组buffer,存放每次读取的内容
        byte[] buffer = new byte[1000];

        //从fileInputStream(d:/我的青春谁做主.txt)中读100个字节到buffer中
        int length = fileInputStream.read(buffer);

        int count = 0;
        while (length != -1) //这次读到了至少一个字节
        {
            System.out.println(length);
            //将buffer中内容写入到输出流(E:\myFile\myPrime.txt)
            fileOutputStream.write(buffer,0,length);

            //继续从输入流中读取下一批字节
            length = fileInputStream.read(buffer);
            count++;
        }
        System.out.println(count);

        fileInputStream.close();
        fileOutputStream.close();

    }

使用字符流读写文件

使用FileReader读取文件

   public static void main(String[] args) throws IOException {
        //
        FileReader fileReader = new FileReader("D:/我的青春谁做主.txt");

        char[] array = new char[100];
        int length = fileReader.read(array);
        StringBuilder sb = new StringBuilder();
        while (length != -1)
        {
            sb.append(array);
            length = fileReader.read(array);
        }

        System.out.println(sb.toString());
        fileReader.close();

    }

BufferedReader类

如何提高字符流读取文本文件的效率?
使用FileReader类与BufferedReader类
BufferedReader类是Reader类的子类
BufferedReader类带有缓冲区
按行读取内容的readLine()方法

image
  public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("D:/我的青春谁做主.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strContent = bufferedReader.readLine();
        StringBuilder sb = new StringBuilder();
        while (strContent != null)
        {
            sb.append(strContent);
            sb.append("\n");
            sb.append("\r");
            strContent = bufferedReader.readLine();
        }

        System.out.println(sb.toString());
        fileReader.close();
        bufferedReader.close();
    }

使用FileWriter写文件

public class WriterFiletTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Writer fw=null;
        try {
              //创建一个FileWriter对象
              fw=new FileWriter("D:\\myDoc\\简介.txt"); 
              //写入信息
              fw.write("我热爱我的团队!");            
              fw.flush();  //刷新缓冲区

        }catch(IOException e){
              System.out.println("文件不存在!");
        }finally{
            try {
                if(fw!=null)
                    fw.close();  //关闭流
             } catch (IOException e) {
                e.printStackTrace();
             }
        }
    }

}

如何提高字符流写文本文件的效率?
使用FileWriter类与BufferedWriter类
BufferedWriter类是Writer类的子类
BufferedWriter类带有缓冲区

image
public class BufferedWriterTest {
    public static void main(String[] args) {
        FileWriter fw=null;
        BufferedWriter bw=null;
        FileReader fr=null;
        BufferedReader br=null;
        try {
           //创建一个FileWriter 对象
           fw=new FileWriter("D:\\myDoc\\hello.txt"); 
           //创建一个BufferedWriter 对象
           bw=new BufferedWriter(fw); 
           bw.write("大家好!"); 
           bw.write("我正在学习BufferedWriter。"); 
           bw.newLine(); 
           bw.write("请多多指教!"); 
           bw.newLine();               
           bw.flush();

           //读取文件内容
            fr=new FileReader("D:\\myDoc\\hello.txt"); 
            br=new BufferedReader(fr); 
            String line=br.readLine();
            while(line!=null){ 
                System.out.println(line);
                line=br.readLine(); 
            }

            fr.close(); 
           }catch(IOException e){
                System.out.println("文件不存在!");
           }finally{
               try{
                   if(fw!=null)
                       fw.close();
                   if(br!=null)
                       br.close();
                   if(fr!=null)
                       fr.close();  
               }catch(IOException ex){
                    ex.printStackTrace();
               }
           }
    }
}

作者:豆约翰
链接:https://www.jianshu.com/p/5759570f9d8b
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是文件? 文件可认为是相关记录或放在一起的数据的集合 JAVA程序如何访问文件属性? JAVA中的文件及目录处...
    十一_2bef阅读 447评论 0 0
  • 什么是文件? 文件可认为是相关记录或放在一起的数据的集合 文件一般存储在哪里? JAVA程序如何访问文件属性? j...
    __豆约翰__阅读 1,366评论 0 5
  • 什么是文件? 文件可认为是相关记录或放在一起的数据的集合 文件一般存储在哪里? JAVA程序如何访问文件属性? j...
    蛋炒饭_By阅读 695评论 0 0
  • java.io.File 类 File类访问文件属性 JAVA中的文件及目录处理类 在Java中提供了操作文件及目...
    小猪Harry阅读 190评论 0 0
  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,415评论 0 4