|
| 1 | +package ssj.algorithm.util; |
| 2 | + |
| 3 | + |
| 4 | +import com.google.common.base.Preconditions; |
| 5 | +import ssj.algorithm.Queue; |
| 6 | +import ssj.algorithm.collections.HashSet; |
| 7 | +import ssj.algorithm.collections.LinkedList; |
| 8 | + |
| 9 | +import java.io.File; |
| 10 | +import java.io.FileNotFoundException; |
| 11 | +import java.util.Scanner; |
| 12 | + |
| 13 | +/** |
| 14 | + * 算算自己写了多少行代码 |
| 15 | + * 遍历的过程其实就是广度遍历 |
| 16 | + * Created by shenshijun on 15/2/27. |
| 17 | + */ |
| 18 | +public class LineCounter { |
| 19 | + private String dir; |
| 20 | + private HashSet<String> suffixs; |
| 21 | + |
| 22 | + public static void main(String[] args) throws FileNotFoundException { |
| 23 | + LineCounter counter = new LineCounter("/Users/shenshijun/IdeaProjects/javaalgithm/src/", new String[]{"java"}); |
| 24 | + System.out.println(counter.count()); |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + public LineCounter(String dir, String[] suffixs) { |
| 29 | + this.dir = dir; |
| 30 | + this.suffixs = new HashSet<>(); |
| 31 | + for (String s : suffixs) { |
| 32 | + this.suffixs.add(s); |
| 33 | + } |
| 34 | + } |
| 35
10000
td> | + |
| 36 | + |
| 37 | + public void addSuffix(String suffix) { |
| 38 | + Preconditions.checkNotNull(suffix); |
| 39 | + suffixs.add(suffix); |
| 40 | + } |
| 41 | + |
| 42 | + public void removeSuffix(String suffix) { |
| 43 | + Preconditions.checkNotNull(suffix); |
| 44 | + suffixs.delete(suffix); |
| 45 | + } |
| 46 | + |
| 47 | + public int count() throws FileNotFoundException { |
| 48 | + File root = new File(dir); |
| 49 | + int result = 0; |
| 50 | + if (root.exists()) { |
| 51 | + Queue<File> queue = new LinkedList<>(); |
| 52 | + queue.appendTail(root); |
| 53 | + while (!queue.isEmpty()) { |
| 54 | + File cur_file = queue.removeHead(); |
| 55 | + if (cur_file.isDirectory() && cur_file.listFiles() != null) { |
| 56 | + for (File f : cur_file.listFiles()) { |
| 57 | + queue.appendTail(f); |
| 58 | + } |
| 59 | + } else if (cur_file.isFile()) { |
| 60 | + for (String suffix : suffixs) { |
| 61 | + if (cur_file.getName().endsWith("." + suffix)) { |
| 62 | + result += countFile(cur_file); |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + return result; |
| 70 | + } |
| 71 | + |
| 72 | + private int countFile(File file) throws FileNotFoundException { |
| 73 | + Preconditions.checkNotNull(file); |
| 74 | + Preconditions.checkArgument(file.isFile()); |
| 75 | + |
| 76 | + int result = 0; |
| 77 | + Scanner sc = new Scanner(file); |
| 78 | + while (sc.hasNext()) { |
| 79 | + result++; |
| 80 | + sc.nextLine(); |
| 81 | + } |
| 82 | + return result; |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | + |
0 commit comments