6.4 通过IO实现文件的读取与写入

6.4 通过IO实现文件的读取与写入

  • 1. File类及常用方法
  • 2. 通过字节字符流实现文件读取与写入
    • 1. 流
    • 2. 字节输入输出流 InputStream与OutputStream
    • 3. 字符输入输出流实现文本读取与写入
    • 4. 字节流与字符流的相互转化
  • 3. 缓冲区及应用
  • 4. 其他流的应用
  • 5. 练习:利用URLConnection对象下载网络图片
  • 6. 总结

1. File类及常用方法

6.4 通过IO实现文件的读取与写入_第1张图片

package com.imooc.io;

import java.io.File;
import java.io.IOException;

public class FileSample {
    public static void main(String[] args) {
        File f = new File("d:/b.txt");
        File d = new File("d:/电影/华语/大陆");
        try {
            boolean r1 = f.createNewFile();
            System.out.println(f.getPath() + "文件创建是否成功:" + r1);
            System.out.println(f.getPath() + "是否存在:" + f.exists());
            System.out.println(f.getPath() + "是否是目录:" + f.isDirectory());
            System.out.println(f.getPath() + "是否是文件:"+f.isFile());
            System.out.println(f.getPath() + "的大小:"+f.length());
            System.out.println(f.getPath() + "的文件名:"+f.getName());
            boolean r2 = f.delete();
            System.out.println(f.getPath() + "文件是否删除成功:" + r2);
            System.out.println(f.getPath() + "是否存在:"+ f.exists());
            boolean r3 = d.mkdirs();
            System.out.println("[" + d.getPath() + "]目录是否创建成功:" + r3);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

2. 通过字节字符流实现文件读取与写入

1. 流


6.4 通过IO实现文件的读取与写入_第2张图片
6.4 通过IO实现文件的读取与写入_第3张图片

2. 字节输入输出流 InputStream与OutputStream

6.4 通过IO实现文件的读取与写入_第4张图片
6.4 通过IO实现文件的读取与写入_第5张图片
6.4 通过IO实现文件的读取与写入_第6张图片
6.4 通过IO实现文件的读取与写入_第7张图片

package com.imooc.io;

import java.io.*;

public class FileCopySample {
    public static void main(String[] args) {
        File source = new File("d:/demo.jpg");
        File target = new File("d:/demo1.jpg");
        InputStream fis = null;
        OutputStream fos = null;
        try {
            //实例化InputStream对象:读文件
            fis = new FileInputStream(source);
            //实例化Outputstream对象:写文件
            fos = new FileOutputStream(target);
            byte[] bs = new byte[1024];
            int len;
            //利用read方法循环读取的字节数据,并进行处理
            while((len = fis.read(bs)) != -1){
                System.out.println(len);
                //将读取到到字节数组写入到输出流
                fos.write(bs,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {        //通过finally块确保fis/fos对象执行close方法
            if(fos != null){
                try {
                    fos.close();//关闭写
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();//关闭读
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. 字符输入输出流实现文本读取与写入

6.4 通过IO实现文件的读取与写入_第8张图片

package com.imooc.io;

import java.io.*;

public class TextFileSample {
    /*FileReader读取文本文件案例*/
    public void readTextFile(){
        Reader reader = null;
        try{
            File file = new File("d:/test.txt");
            //实例化Reader对象
            reader = new FileReader(file);
            int ch = 0;
            //逐个字符读取
            while((ch = reader.read()) != -1){
                System.out.print((char)ch);//UTF-8编码集
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try {
                    //关闭reader对象
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*Writer写入文本文件过程*/
    public void writeTextFile(){
        Writer writer = null;
        try {
            File file = new File("d:/test.txt");
            //创建文件
            if (!file.exists()) {//判断文件是否存在
                file.createNewFile();//不存在,创建对于文件
            }
            //实例化writer对象
            writer = new FileWriter(file);
            //write()方法用于覆盖已有文件内容
            writer.write("这是一个新文件New");
            //append()方法用于在文件末尾追加
            writer.append(":Append内容");
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //关闭writer对象
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args) {
        TextFileSample sample = new TextFileSample();
        sample.writeTextFile();
        sample.readTextFile();
    }
}

4. 字节流与字符流的相互转化

6.4 通过IO实现文件的读取与写入_第9张图片
了解即可

package com.imooc.io;

import java.io.*;

public class TextFileSample {
    /**
     * 字节转字符读取文件内容
     * 字节输入流(InputStream)转字符输入流(InputStreamReader)
     */
    public void isrSample(){
        InputStream fis = null;
        InputStreamReader isr = null;
        try{
            File file = new File("d:/test.txt");
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis,"UTF-8");
            StringBuffer buffer = new StringBuffer();
            while(isr.ready()){
                buffer.append((char)isr.read());
            }
            System.out.println(buffer.toString());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 字节转字符写入文件内容
     * 字节输出流(OutputStream)转字符输出流(OutputStreamWriter)
     */
    public void oswSample() {
        OutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            File file = new File("D:/test.txt");
            //创建文件
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write("这是一个新文件!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        TextFileSample sample = new TextFileSample();
        sample.isrSample();
        sample.oswSample();
    }
}

3. 缓冲区及应用

6.4 通过IO实现文件的读取与写入_第10张图片

package com.imooc.io;

import java.io.*;

public class TextFileSample {
    public void readBuffer(){
        Reader reader =null;
        BufferedReader br = null;
        try{
            File file = new File("d:/FileSample.java");
            reader = new FileReader(file);
            br = new BufferedReader(reader);
            String line = null;//行文本
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (br != null) {
                    br.close();
                }
                if(reader!= null){
                    reader.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        TextFileSample sample = new TextFileSample();
        sample.readBuffer();
    }
}

4. 其他流的应用

6.4 通过IO实现文件的读取与写入_第11张图片

5. 练习:利用URLConnection对象下载网络图片

6.4 通过IO实现文件的读取与写入_第12张图片

package com.imooc.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 根据图片的url下载到本地
 */
public class URLConnectionSample {
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL("https://img-home.csdnimg.cn/images/20240111100221.jpeg");
            //URLConnection对象可根据url获取对应字节
            URLConnection connection = url.openConnection();
            is = connection.getInputStream();
            os = new FileOutputStream("d:/20240111100221.jpeg");
            byte[] bs = new byte[1024];
            int len = 0;
            while((len = is.read(bs)) != -1){
                //System.out.println(len);
                os.write(bs,0,len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os != null){
                    os.close();
                }

                if (is != null) {
                    is.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

6. 总结

6.4 通过IO实现文件的读取与写入_第13张图片
6.4 通过IO实现文件的读取与写入_第14张图片

你可能感兴趣的:(Java工程师2022版,java)