Java基础-FileInputStream字节输入流读取文件方式

package com.hspedu.io_;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;

public class TestFileInputStream {
    @Test
    public void readFile() {
        String filePath = "e:\\JavaIO\\FileInputStream\\test.txt";
        FileInputStream fileInputStream = null;
        int readData = 0;
        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void readFileByArray() {
        String filePath = "e:\\JavaIO\\FileInputStream\\test.txt";
        FileInputStream fileInputStream = null;
        byte[] bytes = new byte[1024];
        int readData = 0;

        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readData = fileInputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, readData));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 需要给定一个int类型的readData接收读取的字符内容,否则会出现乱码

posted @ 2022-04-14 11:31  柯南同学  阅读(491)  评论(0编辑  收藏  举报