Java暑期学习第三十天日报

一、今日学习的内容:

今日学习12.5章的课后习题。

二、遇到的问题:

 对于习题的第二题中统计各字符出现的次数不会,经过网上查找资料进行学习解决了问题。关于第三题log4j日志方面的知识点还未学习,准备明天进行学习所以未做,准备学习后进行操作。

三、明日计划:

明天计划学习log4j日志的内容。

 

今天学习的具体内容如下:

1.比较File Input Stream流的read方法和FileReader的read方法有什么异同点

相同点:都能够对文件中的数据和文本进行读取。

不同点:InputStream提供的是字节流的读取,而非文本读取,这是和Reader类的根本区别。两者读写单位不同、处理对象不同。用Reader读取出来的是char数组或者String ,使用InputStream读取出来的是byte数组。

 

import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
public class readAndInput {
    public static void main(String []args)throws IOException{
        FileInputStream fis=null;
         fis=new FileInputStream("D:\\hello3.txt");
        System.out.println("用FileInputStream的read方法进行数据读取:");
        int len1=0;
        byte[] bufs=new byte[1024];
        while((len1=fis.read(bufs))!=-1) {
            String s1=new String(bufs,0,len1);
            System.out.println(s1);
        }
        fis.close();
        InputStreamReader fr=new FileReader("D:\\hello3.txt");
        int len=0;
        char[] buf=new char[1024];
        System.out.println("用FileReader的read方法进行数据读取:");
        while((len=fr.read(buf))!=-1) {
            String s=new String(buf,0,len);
            System.out.println(s);
        }
        fr.close();
    }
        
}

测试截图;

         

 

 

 

 

2.编写一个程序,把一段英文字符写进“D:\\data.txt"文件中,然后从文件中读取第一行数据,并统计个字符出现的次数

package excise;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.util.HashMap;
public class t1 {
    public static void main(String[] args) throws IOException{
        Scanner sc=new Scanner(System.in);
        FileOutputStream fos=new FileOutputStream("D:\\data.txt");
        System.out.println("请输入一段英文字符:");
        String str=sc.nextLine();
        byte [] buf=str.getBytes();
        fos.write(buf);
        fos.close();
        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("D:\\data.txt")));
        String s=br.readLine();    
        System.out.println("该行数据为:"+s);
        count(s);
        
        }
    public static void count(String s) {
        char[] chars=s.toCharArray();
        HashMap<Character,Integer>hm=new HashMap();
        for(char c:chars) {
            if(!hm.containsKey(c))
                hm.put(c,1);
            else
                hm.put(c, hm.get(c)+1);
        }
        for(Character key:hm.keySet())
            System.out.println(key+": "+hm.get(key));
    }
    

}

测试截图:

 

posted on 2020-08-04 15:36  桑榆非晚柠月如风  阅读(128)  评论(0编辑  收藏  举报