java读取txt文件,并统计每行中每个字母出现的次数,并将产生的数字保存到一个新的txt文件中(有加分)

2024-11-25 16:26:43
推荐回答(2个)
回答1:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
 * 统计一部小说中文字数量
 *
 */
public class Demo10 {
  static int count = 0;
  public static void main(String[] args)throws IOException{
    String file = "src/javase2/day03/demo.txt";
    Map map = count(file);
    List> entrys =
     new ArrayList>(map.entrySet());
    Collections.sort(entrys,
        new Comparator>() {
      public int compare(Entry o1,
          Entry o2) {
        return -(o1.getValue() - o2.getValue());
      }
    });
    int all = map.size();
    System.out.println("不重复字符数量:"+ all);
    System.out.println("总字符数量:"+ count);
    for(int i=0; i<10; i++){
      Entry entry = entrys.get(i);
      char c = entry.getKey();
      int val = entry.getValue();
      System.out.println(c+":"+val+","+(val*100.0/count)+"%");
    }
  }
  public static Map count(String file)
    throws IOException {
    InputStreamReader in =
      new InputStreamReader(
          new BufferedInputStream(
              new FileInputStream(file)),"GBK");
    Map map =
      new HashMap();
    Set ignoreChars = new HashSet();
    //ignoreChars 忽略的字符
    ignoreChars.add('\n');
    ignoreChars.add('\r');
    ignoreChars.add(',');
    ignoreChars.add('。');
    ignoreChars.add(' ');
    ignoreChars.add(' ');//...
    int c;
    while((c = in.read())!=-1){
      char ch = (char)c;
      if(ignoreChars.contains(ch)){
        continue;
      }
      count++;
      Integer val = map.get(ch);
      map.put(ch, val == null ? 1 : val+1);
    }
    in.close();
    return map;
  }
}

翻了一下以前的案例,给你找到了  你可以试试  



下面的这个是一个IO 的工具类  

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import javax.imageio.stream.FileImageInputStream;
/**
 * IO 工具类
 */
public class IOUtils {
                                                
  public static Object deepCopy(Object obj) {
    try {
      ByteArrayOutputStream buf =
        new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(buf);
      oos.writeObject(obj);// 将对象序列化到byte数组流中
      oos.close();
      byte[] ary = buf.toByteArray();
      ObjectInputStream ois = new ObjectInputStream(
          new ByteArrayInputStream(ary));
      Object o = ois.readObject();// 从byte数组流中反序列化对象
      ois.close();
      return o;
    } catch (Exception e) {// 异常捕获再抛出, 将异常转换为运行时异常
      throw new RuntimeException(e);
    }
  }
                                                
  /**
   * 复制文件功能: 将文件src复制为dst
   * 只能复制文件! 不支持文件夹的复制!
   * @param src 源文件
   * @param dst 目标文件
   */
  public static void cp(String src, String dst){
    try {
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dst);
      byte[] buf = new byte[10*1024];
      int count;
      while((count=in.read(buf))!=-1){
        //System.out.println(count);
        out.write(buf, 0, count);
      }
      //System.out.println("结束了:"+count);
      in.close();
      out.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  public static void cp2(String src, String dst){
    try {
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dst);
      int b;
      while((b=in.read())!=-1){
        out.write(b);
      }
      in.close();
      out.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
                                                
  /**
   * 实现将文件读取到一个byte数组
   */
  public static byte[] read2(String filename){
    try{
      InputStream in = new FileInputStream(filename);
      byte[] buf = new byte[in.available()];
      in.read(buf);
      in.close();
      return buf;
    }catch(IOException e){
      throw new RuntimeException(e);
    }
  }
                                                
  public static void print(File file){
    try{
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      int b; int i=1;
      while((b=raf.read())!=-1){
        if(b<=0xf)
          System.out.print("0");
        System.out.print(Integer.toHexString(b)+" ");
        if(i++%16 == 0){
          System.out.println();
        }
      }
      System.out.println();
      raf.close();
    }catch(IOException e){
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  public static void print(byte[] buf){
    int i=1;
    for(int b : buf){
      b = b & 0xff;
      if(b<=0xf)
        System.out.print("0");
      System.out.print(Integer.toHexString(b)+" ");
      if(i++%16 == 0){
        System.out.println();
      }
    }
    System.out.println();
  }
  /**
   * 将小文件 一次性 读取到 byte数组中返回
   * @param file 文件名
   * @return 全部文件内容
   */
  public static byte[] read(String file){
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      byte[] buf = new byte[(int)raf.length()];
      raf.read(buf);
      raf.close();
      return buf;
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  public static byte[] read(File file){
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      byte[] buf = new byte[(int)raf.length()];
      raf.read(buf);
      raf.close();
      return buf;
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  /**
   * 在控制台上按照16进制格式输出文件的内容
   * 每16个byte为一行
   * @param file 文件名
   * @throws RuntimeException 如果文件读取失败,跑出异常
   */
  public static void print(String file){//IOUtils.java
    try{
      RandomAccessFile raf=
        new RandomAccessFile(file, "r");
      int b; int i=1;
      while((b=raf.read())!=-1){
        if(b<=0xf){ System.out.print('0'); }
        System.out.print(Integer.toHexString(b)+" ");
        if(i++%16==0){ System.out.println(); }
      }
      System.out.println();
      raf.close();     
    }catch(IOException e){
      throw new RuntimeException(e);
    }
  }
}

回答2:

逐行读,逐个字母判断,用Map统计。