# IO Lab作法 ###### tags: `JAVA` # 12/18Lab ## 作法一 1. 設置TreeSet比較資料大小,(利用.length())。 2. 利用for迴圈,將File[]陣列中的資料輸入至Set中。 3. 用進階for迴圈,將資料印出。 ``` package oi; import java.io.File; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class FileTest { public static void main(String[] args) { File fileLab = new File("D:\\Java\\JavaWorkspace\\JavaLab\\src"); File[] filesLab = fileLab.listFiles(); Set<File> fileSet = new TreeSet<>(new Comparator<File>() { @Override public int compare(File o1, File o2) { if(o1.length() < o2.length()) { return -1; }else if(o1.length() > o2.length()) { return 1; }else { return 0; } } }); for(File file2 : filesLab) { if(!file2.isDirectory()) { fileSet.add(file2); }else { continue; } } for(File file3 : fileSet) { System.out.println("檔案名稱 : "+file3.getName()+" 檔案大小 : "+file3.length()+" byte"); } //----------------------------------------------------------------------------------------------------- long totalValue = 0; int sum = 0; for(File total:filesLab ) { if(!total.isDirectory()) { sum += 1; totalValue = totalValue + total.length(); }else { continue; } } System.out.println("檔案總數 : "+sum+" 檔案大小總和 : "+totalValue+" byte"); //------------------------------------------------------------------------------------------------------ } } ``` ## 作法二 1. 利用for迴圈,將File[]陣列中的資料輸入至HashMap中。 (Key值為檔案名稱,Value值為檔案大小)。 2. 建立TreeSet用來比較資料大小,(利用.getValue)。 3. 將Map轉成Entry的方式存入Set。(利用.entrySet()) 4. 將步驟3轉好的Entry匯入TreeSet。(利用.addAll()指令) [.addAll指令說明](https://vimsky.com/zh-tw/examples/usage/set-addall-method-in-java-with-examples.html) 5. 用進階for迴圈,將資料印出。 ``` package oi; import java.io.File; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; public class TestEntryLab { public static void main(String[] args) { File file = new File("D:\\Java\\JavaWorkspace\\JavaLab\\src"); File[] file2 = file.listFiles(); Map<String, Long> map = new HashMap<>(); for(File file3 : file2) { if(!file3.isDirectory()) { map.put(file3.getName(), file3.length()); }else { continue; } } Set<Entry<String, Long>> set = new TreeSet<>( new Comparator<Entry<String, Long>>() { @Override public int compare(Entry<String, Long> o1, Entry<String, Long> o2) { if(o1.getValue() < o2.getValue()) { return -1; }else if(o1.getValue() > o2.getValue()) { return 1; }else { return 0; } } }); set.addAll(map.entrySet()); for(Entry<String, Long> fileEntry : set) { System.out.println("檔案名稱 : "+ fileEntry.getKey()+" 檔案大小 : "+fileEntry.getValue()+" byte"); } } } ```