java按行和字符读取文件内容

public class BufferedInputFile {   
    //按行读取
    public static String read(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s=reader.readLine())!=null){
               sb.append(s+"\n");
        }
        reader.close();
        return sb.toString();
    }

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

      //  System.out.println(read("D:\\BaiduNetdiskDownload\\work\\zzy\\src\\main\\java\\com\\zzy\\io\\DirList.java"));
       //按字符读取
        StringReader reader = new StringReader(BufferedInputFile.read("D:\\BaiduNetdiskDownload\\work\\zzy\\src\\main\\java\\com\\zzy\\io\\DirList.java"));
        int c;
        while ((c=reader.read())!=-1){
            System.out.println((char) c);
        }
        reader.close();

    }
}

output:
在这里插入图片描述

//按字节读取字符
DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedInputFile.
        read("D:\\BaiduNetdiskDownload\\work\\zzy\\src\\main\\java\\com\\zzy\\io\\DirList.java").getBytes()));
while (in.available()!=0){
    System.out.println((char) in.readByte());
}
in.close();
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页