读取文件
工作内容
题目1:
1)查找一个目录下,所有文件中数字、字母(大小写不区分)、汉字、空格的个数、行数。
2)将结果数据写入到文件中。
文件格式如下:
数字:198213个
字母:18231个
汉字:1238123个
空格:823145个
行数:99812行
数字0:123个
数字1:1214个
数字2:23423个
……
字母A:754456个
字母B:7567个
字母C:456456个
使用方法
运用了i/o流的读和写,正则表达式,封装:
思想:一开始我用了char型,就是以字符为单位的读,但是这个思想有许多的dug比如说不能判断行数,换行认为空格,
后来用了以行为单位的读,这个方法读多少行就有多少行数
while ( (str11 =br.readLine()) != null) {// 判断是否是最后一行
char[] c = str11.toCharArray();//把字符转换为char数组
没有实现的功能:
1 不知道如何用正则表示汉字,
2 想用封装来完成各个的个数没有完成,。
3 写出如何获取行数。
体会:
发现自己还差的很远:
1. 字符之间的转换,
2. i/o流的许多细节还不够熟练,
3. 正则表达式今天可以说是第一次用,也是现学现用。
4.正则和字符串之间的运用 Pattern.compile("[a-zA-Z]").matcher(str1).matches()
5.读取的时候出现中文乱码
6.封装的时候封装不了大功能,可以封装里面的小功能。
没有实现的功能还的看书学习。
实例:
/** * 读取文件 * * @param str */ public String readFile(String str) { int s = 0; int k = 0; int t = 0; int d = 0; int h = 0; String str2 = ""; File f = new File(str); try { FileInputStream fis = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fis,"gbk"); BufferedReader br = new BufferedReader(isr); try { String str11; while ( (str11 =br.readLine()) != null) {// 判断是否是最后一行 char[] c = str11.toCharArray();//把字符转换为char数组 for (int i = 0; i < c.length; i++) { String str1 = String.valueOf(c[i]); // char转换string if (Pattern.compile("[a-zA-Z]").matcher(str1).matches()) { s++; } // 字母的个数 if (Pattern.compile("[0-9]").matcher(str1).matches()) { k++; } // 数字的个数 if (Pattern.compile("[[^\\x00-\\xff]]").matcher(str1).matches()) { t++; } // 汉字的个数 if (Pattern.compile("[\\s]").matcher(str1).matches()) { d++; } // 空格的个数 // if (Pattern.compile("[\\t]").matcher(str1).matches()) // { // h++; }// } h++; // 回车的个数 } str2 = "字母:" + s + "个\t\n" + "数字:" + k + "个\t\n" + "汉字:" + t + "个\t\n" + "空格:" + d + "个\t\n" + "回车:" + h + "个\t\n"; System.out.println(str2); } catch (IOException e) { System.out.println("读取失败!!!"); } finally { try { if(br!=null){ br.close(); } if(isr!=null){ isr.close(); } if(fis!=null){ fis.close(); } } catch (IOException e) { System.out.println("关闭不成功!!"); } } } catch (FileNotFoundException e) { System.out.println("输入失败!!!"); } return str2; } /** * 写出 * * **/ public void writeFile(String str, String paths) { try { File file = new File(paths); FileOutputStream fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile(); } byte[] contentInBytes = str.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("写入失败!!!"); } } /** * 读写结合 * */ public class Combine { public void combineFile(String readPaths, String writePaths) { Read r = new Read(); String str1 = r.readFile(readPaths); Write w = new Write(); w.writeFile(str1, writePaths); } } public class Test { public static void main(String[] args) { Combine c = new Combine(); String writePaths="E:\\key1.txt"; String readPaths="E:\\key.txt"; c.combineFile(readPaths, writePaths); } } /** * 字符与正则匹配 str 字符 zhz 正则 * @return */ public boolean readNumber(String zhz, String str) { return Pattern.compile(zhz).matcher(str).matches(); }