这道题与下面这道题出自于我今天的面试,实现的需求大同小异。但是我却不会,没能做出来,这里做一下笔记。
package com.example.study_source.pager;
import org.junit.Test;
import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class FileStatisticsTest {
private static long getNumCnt(String str) { long cnt = 0L; String regex = "\\d"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
private static long getSpaceCnt(String str) { long cnt = 0L; String regex = "\\s"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
private static long getChineseCnt(String str) { long cnt = 0L; String regex = "[\\u4e00-\\u9fa5]"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
private static long getLetterCnt(String str) { long cnt = 0L; String regex = "[a-zA-Z]"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
private static long getPunctuationCnt(String str) { long cnt = 0L; String regex = "[\\pP\\p{Punct}]"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
private static long getCharCnt(String str) { long cnt = 0L; String regex = "."; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(str); while (matcher.find()) { cnt++; } return cnt; }
@Test public void testCnt() { String filePath = "E:\\webp\\test1\\2.txt"; int lineCnt = 0, numCnt = 0, spaceCnt = 0, chineseCnt = 0, letterCnt = 0, punctuationCnt = 0, charCnt = 0; try { File file = new File(filePath); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String strLine = ""; while ((strLine = bufferedReader.readLine()) != null) { lineCnt++; numCnt += getNumCnt(strLine); spaceCnt += getSpaceCnt(strLine); chineseCnt += getChineseCnt(strLine); letterCnt += getLetterCnt(strLine); punctuationCnt += getPunctuationCnt(strLine); charCnt += getCharCnt(strLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("该文件总共: " + lineCnt + "行," + numCnt + " 个数字," + spaceCnt + " 个空格," + chineseCnt + " 个汉字," + letterCnt + " 个字母," + punctuationCnt + " 个标点符号," + charCnt + " 个字符。"); }
private void copyFile(File file) throws Exception { FileInputStream fis = new FileInputStream(file); String outputPath = "E:\\webp\\copy.txt"; File file1 = new File(outputPath); FileOutputStream fos = new FileOutputStream(file1); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); fis.close(); System.out.println("finished ..."); }
@Test public void test() throws Exception { String url = "E:\\webp\\test1\\1.txt"; File file = new File(url); copyFile(file); } }
|