Java File类、IO流

179 阅读3分钟

File类

File类描述的是一个文件或文件夹。
File 定义一些与平台无关的方法来操作文件 常见的操作:

image.png

image.png

        try {
            //这个创建只是在描述这个文件或者文件夹
//            File file = new File("E:\movie\test\qaz.txt");
            //createNewFile  创建一个文件,如果不存在,会创建
//            System.out.println(file.createNewFile());
            File file2 = new File("E:\movie\test\qaz");
//            File file3 = new File("E:\mdf\test\qaz");
            //可以创建一个文件夹,但是之前已经存在一个文件与其同名,则无法创建
//            System.out.println(file2.mkdir());
            //创建文件夹,这会创建路径中所有不存在的目录
//            System.out.println(file3.mkdirs());
//            System.out.println(file2.delete());
//            System.out.println(file2.renameTo(new File("E:\movie\test\qa")));
            File f4 = new File("E:\movie");
            for (File obj :f4.listFiles() ) {
                System.out.println(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

获取指定目录下的所有文件路径以及文件名

public static void main(String[] args) {
    File file = new File("E:\movie\study");
    getFile(file);
}
public static void getFile(File file){
    if(file.exists()){
    //判断是否是文件夹
    if(file.isDirectory()){
        File[] f= file.listFiles();
        for (File val: f) {
            getFile(val);
        }
    }else{
        System.out.println(file.getAbsolutePath() +"\t" +"文件名字:" + file.getName());
    }
    }
}

使用File.separatorChar,这个值会根据系统得到相应的分隔符。

字节流

caca9aeef927714fc4f1414700841e4b.jpeg

image.png

//输出流 java.io.OutputStream
 //输入流 java.io.InputStream

 //输入流:读取外部资源放入JVM
 //输出流:将JVM的资源写入到外部资源
 try {
     //打开流(创建流)
     InputStream in = new FileInputStream("E:\movie\test\qa.txt");
     //1、打开文件输出流,流的目的地是指定的文件 这个步骤会开始创建文件 Out
     File file = new File("E:\movie\test\dfad\dfd");
     if (!file.exists()) {
         file.mkdirs();
     }
     OutputStream out= new FileOutputStream("E:\movie\test\dfad\dfd\lala.txt");
     //通过流获取内容
     //2、通过流向文件写数据 Out
     int len;
     while ((len = in.read()) != -1 ){
         System.out.print((char) len);
         out.write(len);
     }
     //3、刷新缓存区
     out.flush();

     //4、用完后,关闭资源流       out先关
     out.close();
     in.close();
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 } catch (IOException e) {
     e.printStackTrace();
 }
public static void main(String[] args) {
    String path = "E:\movie\test\qa.txt";
    writeFileTest(path);
    readFileInputStream(path);
}


//读取文件内容
public static void readFileInputStream(String path){
    try {
        InputStream fileIn = new FileInputStream(path);
         int len = 0;
        while ((len = fileIn.read()) != -1){
            System.out.print((char) len);
        }
        fileIn.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//写入文件内容
public static void writeFileTest(String path){
    try {
        File file = new File(path);
        OutputStream fileOut = new FileOutputStream(file);
        fileOut.write("ghghg".getBytes());
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

字符流

image.png

public static void main(String[] args) {
    try {
        //zifuliu基于字节流,所以在读写的时候,都要依赖字节流
        BufferedWriter writer  = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream("E:\movie\test\qa.txt",true),"UTF-8"));
        writer.write("你在吗dgdsgdfgfg");
        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(new FileInputStream("E:\movie\test\qa.txt"),"UTF-8"));
        char[] ch = new char[1024];
        int len;
        while((len = in.read(ch)) != -1){
            System.out.println(new  String(ch,0,len));
        }
        in.close();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

缓存区

缓冲区的出现大大提高了对流的操作效率,原理:其实就是将数组进行封装。

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    //不采用缓存区和采用缓存区差别很大,加了缓存区能够快速地写入和读取。
    try {
        File file1 = new File("E:\movie\test\qa\【Java SE】37.静态修饰符_高清 1080P.mp4");
        InputStream in = new FileInputStream(file1);
        OutputStream out= new FileOutputStream("E:\movie\test\qa\dsfd.mp4");
        int len;
        //采用缓存区
        byte[] b = new byte[1024 * 2];
        while ((len = in.read(b)) != -1 ){
            out.write(b,0,len);
        }
        //3、刷新缓存区
        out.flush();
        out.close();
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    System.out.println(endTime - startTime);
}

对象流

18945f367ef9b97c6237dfbb0b5814c.png

f3863fa1a2b939e9d546eccab845fdc.png

//1、声明类实现接口,是一个标示器,没有要实现的方法。

public class IO implements Serializable {
    //序列化编码,在每次修改这个类的时候,会发生变化
    static final long serialVersionUID = 1L;
    String name;
    String val;
    String na;
    public void a(){
        System.out.println(name + "在干坏事");
    }

}
 public static void main(String[] args) {
        try {
            ObjectInputStream in= new ObjectInputStream(new FileInputStream("E:\movie\test\dfasd"));
            IO a = (IO) in.readObject();
            a.a();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
//        extracted();
    }

private static void extracted(){
    try {
        //2、新建对象
        IO a =  new IO();
        a.name = "杨某";
        a.val = "看图";
        a.a();
        //3、新建字节流对象(FileOutputStream)进序列化对象保存在本地文件中。如果没有该文件,利用输入流。
        FileOutputStream out = new FileOutputStream("E:\movie\test\dfasd");
        //4、新建ObjectOutputStream对象,调用writeObject方法序列化对象
        ObjectOutputStream obj = new ObjectOutputStream(out);
        //5、writeObject方法会执行两个工作,序列化对象,然后将序列化的对象写入文件中。
        obj.writeObject(a);

        //6、异常处理和流的关闭动作要执行
        obj.flush();
        obj.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}