IO流

字节流:

public class FileByte {

    public static void main(String[] args) throws Exception{
        byte[] tom=new byte[100];
        int b=0;
       FileInputStream fi=new FileInputStream("D://1.txt");
        BufferedInputStream bf=new BufferedInputStream(fi); //缓冲
         while((b=bf.read(tom))!=-1) {
            String s=new String(tom,0,b);////得到数组tom中从0到b的字节,因为b是实际读取到的字节个数
            System.out.println(s);
        }
        bf.close();
    }
}

结果有乱码:

 

 

 

字符流:

public class FileChar {

    public static void main(String[] args) throws Exception{
        char[] tom=new char[100];
        int b=0;
        FileInputStream fi=new FileInputStream("D://1.txt");
        // 字符流才可以指定编码
        BufferedReader br= new BufferedReader(new InputStreamReader(fi,"GBK"));
        while((b=br.read(tom))!=-1) {
            //System.out.println((char)b);
            String s=new String(tom,0,b);////得到数组tom中从0到b的字节,因为b是实际读取到的字节个数
            System.out.println(s);
        }
        br.close();
    }
}

无乱码:

 

 

 找出两个文件夹中相同的单词

package arithmetic;

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

public class FileCounts{

    public static String[] getFile(String file) throws Exception{
        InputStreamReader rd = new InputStreamReader(new FileInputStream( file), "GBK");
 
        BufferedReader bd=new BufferedReader(rd);

        StringBuffer sb=new StringBuffer();
        String a=null;
        while ((a=bd.readLine())!=null) {
            sb.append(a);
            sb.append("\n");
        }
        bd.close();
        String[] words=sb.toString().split("[^a-zA-Z]+");
     
        return words;
    }

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

        String[] s1=getFile("D:\\1.txt");
        String[] s2=getFile("D:\\2.txt");
 
        List<String> list1=new ArrayList<String>(Arrays.asList(s1));
        List<String> list2=new ArrayList<String>(Arrays.asList(s2));
        //计算交集,存入list1中
        list1.retainAll(list2);
        Set set=new HashSet(list1);
        set.toArray(new String[]{});

        System.out.println(   set);

    }



}

 

posted @ 2020-03-23 17:24  你猜lovlife  阅读(89)  评论(0)    收藏  举报