Java学习——day 16

主要内容

  • 使用输入流和输出流实现文件的拷贝
  • 字符流

笔记详情

1. 使用输入流和输出流实现文件的拷贝

import java.io.*;
import java.util.Arrays;

/**
 * 使用输入流和输出流实现文件的拷贝
 */
public class Demo05 {

    public static void main(String[] args) throws FileNotFoundException, IOException {

        // 建立文件的联系
        File src = new File("src/file/1.jpg");
        File dest = new File("src/file/2.jpg");

        // 选择流
        InputStream is = new FileInputStream(src);
        OutputStream os = new FileOutputStream(dest);
        
        byte[] data = new byte[10];       // 每次读取和写入的字节大小
        int len = 0;

        // 不断读取和写入
        while ((len = is.read(data)) != -1) {
            os.write(data);
            os.flush();
        }

        // 关闭的时候,先打开的后关闭
        os.close();
        is.close();
    }
}

2. 字符流

Java中的字符流和字节流的用法大同小异,但是不同的是字节流可以处理一切文件(纯文本、音视频等等),但是字符流只能处理出文本文件。之前的文章中Java学习——day 15介绍过字节流,这里就不过多介绍,直接给出两个实例:

实例1:使用字符流实现文件的读取
import java.io.*;
import java.util.Arrays;

public class Demo07 {

    public static void main(String[] args) {

        File txtFile = new File("src/file/test.txt");
        
        Reader readerTxt = null;

        try {
            readerTxt = new FileReader(txtFile);
            char[] flush = new char[5];     // 每次读取文件的内容
            int len;
            while ((len = readerTxt.read(flush)) != -1) {
                System.out.println(new String(flush, 0, len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件读取失败");
        } finally {
            try {
                readerTxt.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件关闭失败");
            }
        }
    }
}
实例2:使用字符流实现文件的写出
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Demo08 {

    public static void main(String[] args) {

        File txtFile = new File("src/file/1.txt");

        Writer wFile = null;

        try {
            wFile = new FileWriter(txtFile, true);       // 以追加的形式写入文件
            String src = "坚定目标,永不放弃!";
            wFile.write(src);
            wFile.flush();      // 写出文件之后强制刷新
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件打开失败");
        } finally {
            try {
                wFile.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件关闭失败");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/fengzhen8023/article/details/86561257