Authored by zhaoyue

Can read local report

  1 +package main.java.com;
  2 +
  3 +
  4 +import java.io.BufferedReader;
  5 +import java.io.File;
  6 +import java.io.FileInputStream;
  7 +import java.io.InputStreamReader;
  8 +import java.util.HashSet;
  9 +import java.util.Set;
  10 +
  11 +/**
  12 + * Created by zhaoyue on 2017/3/7.
  13 + */
  14 +public class FileUtil {
  15 + /**
  16 + * 功能:Java读取txt文件的内容
  17 + * 步骤:1:先获得文件句柄
  18 + * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
  19 + * 3:读取到输入流后,需要读取生成字节流
  20 + * 4:一行一行的输出。readline()。
  21 + * 备注:需要考虑的是异常情况
  22 + *
  23 + * @param filePath
  24 + */
  25 + public static Set<String> readTxtFile(String filePath) {
  26 + Set<String> resSet = new HashSet<>();
  27 + try {
  28 + String encoding = "GBK";
  29 + File file = new File(filePath);
  30 + if (file.isFile() && file.exists()) { //判断文件是否存在
  31 + InputStreamReader read = new InputStreamReader(
  32 + new FileInputStream(file), encoding);//考虑到编码格式
  33 + BufferedReader bufferedReader = new BufferedReader(read);
  34 + String lineTxt = null;
  35 + while ((lineTxt = bufferedReader.readLine()) != null) {
  36 + resSet.add(lineTxt.toLowerCase().trim());
  37 + }
  38 + read.close();
  39 + } else {
  40 + System.out.println("找不到指定的文件");
  41 + }
  42 + } catch (Exception e) {
  43 + System.out.println("读取文件内容出错");
  44 + e.printStackTrace();
  45 + }
  46 + return resSet;
  47 +
  48 + }
  49 +
  50 + public static void main(String argv[]) {
  51 + String filePath = "C:\\Users\\zhaoyue\\Desktop\\ids";
  52 +// "res/";
  53 + Set<String> resSet = readTxtFile(filePath);
  54 + for (String line : resSet) {
  55 + System.out.println(line);
  56 + }
  57 + }
  58 +
  59 +
  60 +}
  61 +