2015-05-03 87 views
-1

我寫了一個java代碼,用於使用hashmap來計算指令頻率。現在我想爲一個整個文件夾運行這個文件,它有幾個.txt文件。我怎樣才能運行我的Java程序的整個文件夾?

class HashMapCount 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     HashMap h=new HashMap();       
     FileInputStream fin=new FileInputStream("C:\\test.txt"); 
     BufferedReader br=new BufferedReader(new InputStreamReader(fin)); 
     String n; 
     while((n=br.readLine())!=null) 
       { 
        if(h.containsKey(n)) 
         { 
          int i=(Integer)h.get(n); 
          h.put(n,(i+1)); 
         } 
        else 
          h.put(n, 1); 
       } 

    Set setOfKeys = h.keySet(); 

    Iterator iterator = setOfKeys.iterator(); 

    while (iterator.hasNext()) 
     { 
      String key = (String) iterator.next(); 

      Integer value = (Integer)h.get(key); 

      System.out.println("Key: "+ key+", Value: "+ value);  
      } 
    } 
} 
+0

分享你的努力 –

+0

Svarog,幫助你一個樣本 –

+0

我想爲所有文件使用單個hasmap。那麼在我的代碼片段中,我在哪裏使用@svarog建議的Iterator進行文件遍歷? –

回答

0
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.HashMap; 

public class IsFolderSubdirectory { 

    public static HashMap h = new HashMap(); 

    public static void addtoHashMap(File filename) { 

     FileInputStream fin; 
     try { 
      fin = new FileInputStream(filename); 
      BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
      String n; 
      try { 
       while ((n = br.readLine()) != null) { 
        if (h.containsKey(n)) { 
         int i = (Integer) h.get(n); 
         h.put(n, (i + 1)); 
        } else 
         h.put(n, 1); 
       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    public void isfolder(File findfile) { 
     if (findfile.isDirectory()) { 
      System.out.println(findfile + "is a directory"); 
      String[] directoryContents = findfile.list(); 
      for (int i = 0; i < directoryContents.length; i++) { 
       File newpath = new File(findfile + "/" + directoryContents[i]); 
       isfolder(newpath); 
      } 
     } else { 
      IsFolderSubdirectory.addtoHashMap(findfile); 
     } 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     String pathname = "GIVE YOUR PATH HERE"; 
     File file = new File(pathname); 
     String[] directoryContents = file.list(); 
     IsFolderSubdirectory ifs = new IsFolderSubdirectory(); 

     for (int i = 0; i < directoryContents.length; i++) { 
      File newpath = new File(pathname + "/" + directoryContents[i]); 
      ifs.isfolder(newpath); 
     } 

    } 
} 

檢查文件夾中包含的文件或文件夾。如果文件發現調用addtoHashMap在hashmap中添加它,則迭代它直到它找到該文件。對所有存在的子目錄和存在的文件重複相同的操作。

+0

Thankyou的答案,但我的hasmap的實際功能是計算頻率並且不存儲文件名。我只想使用單個哈希映射來計算來自所有文件的指令頻率。 –

+0

我已經使用了staic hashmap,因此它將爲所有文件使用相同的hashmap。 –

1

您可以使用一個Iterator遍歷文件夾中的文件,像這樣

File folder = new File("/"); // path of folder 
File[] files = folder.listFiles(); 

for (File file : files) { 
    if (file.isFile() && file.endsWith(".txt")) { 
     // your file handling logic here 
    } 
} 
+0

我想爲所有文件使用單個hasmap。那麼我在哪裏使用迭代器在我的代碼片段中遍歷文件? –

+0

for循環是迭代器,請參閱:http://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html,在迭代器內執行hashmap操作 – svarog

0

我試着問在這裏找到我的問題一個一個解決方案:

Hashmap single key holding a class. count the key and retrieve counter

,然後看到你的questin,讓我評論它,看我怎麼解決你的問題。請給我反饋。


所以首先讓我們看看我們所要做的:

  1. 設置你的文件在它(OriginalDocFolder
  2. 設置路徑爲存儲原始文件夾的路徑(TargetDocFolder
  3. 路徑這兩個文件夾,並執行以下操作:個ReadAllFilesInOrignalFolderCountAndWriteSeparateFilesInTargetFolders

    我假設你的輸入文件都是這樣命名* 00001.txt」與其他的格式如下聰明的讓我知道要更新我的一些代碼爲你。

    experiment 
    investig 
    aerodynam 
    wing 
    slipstream 
    brenckman 
    

讓我改變主類中的以下內容:

,我在一個叫FileManipulation後來,我們在這裏調用函數從該類類寫作一切在你的主要班級。 (A)我在我的項目中添加了一個包,並將其命名爲ed.unlv.filemanimulation 然後(B)添加了一個名爲FileManipulation的類。java的到packacge這裏導入它由以下


import edu.unlv.filemanipulation.*; 
import java.util.ArrayList; 
import edu.unlv.utility.*; 
/** 
* @author Dara Nyknahad 
*/ 
public class HashMapCount{ 

public static void main(String[] args) throws Exception { 

//creating output folders 
// to do: err handling if the folders exist 
FileManipulation.createOutputFoldersAt("C:\\Dara\\Data\\Output\\"); 
String OriginalDocFolderPath="C:\\Dara\\Data\\Output\\Original\\"; 
String frequenceyDocFolderPath="C:\\Dara\\Data\\Output\\Frequency\\"; 
ArrayList<String> listOfOriginalFiles=new ArrayList<>(); 
FileManipulation.getFilePathFrom(OriginalDocFolderPath, listOfOriginalFiles); 
String [] arrayOfOriginalFileAddresses = listOfOriginalFiles.toArray(new  String[listOfOriginalFiles.size()]); 
//Count the words 
FileManipulation.countDistinctWordVersion1(arrayOfOriginalFileAddresses, frequenceyDocFolderPath); 
    } 
} 

現在,你可以看到我們改變了countDistinctWord的簽名接收陣列包含所有文件和我們將其設置爲目標的文件夾。

這裏我正在給你寫上面的想法和方法FileManipulation class。

注:以下代碼基於JDk8也NIO,所以你需要使用java8。

package edu.unlv.filemanipulation; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.nio.charset.Charset; 
import java.nio.file.FileSystems; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.TreeMap; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import java.util.regex.Pattern; 
import java.util.Set; 

/** 
* @author Dara Nyknahad 
*/ 
public class FileManipulation { 
    public static void getFilePathFrom(String FolderPath, ArrayList<String> listOfFiles){ 
       //getting a folder filling an array that include the address of the files 
       try { 
       Files.walk(Paths.get(FolderPath)).forEach(filePath -> { 
          if (Files.isRegularFile(filePath)) { 
           listOfFiles.add(filePath.toString()); 
           //System.out.println("Reading file: "+ filePath); 
          } 
        }); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      } 
    public static void createOutputFoldersAt(String outputFolder) throws Exception{ 
     //creating a desired folder 
    Path frequnceyFolder=FileSystems.getDefault().getPath(outputFolder+"Frequency"); 
      try { 
        Files.createDirectory(frequnceyFolder); 
         System.out.println("Frequency folder created"); 
      } catch (IOException e) { 
        System.err.println(e.toString()); 
      }   
} 

public static void countDistinctWordVersion1(String[] arrayOfStemmedFileAddresses, String frequenceyDocFolderPath) throws Exception{  

     System.out.println("Counting the words are in progress ..."); 

     for(int i=0;i<arrayOfStemmedFileAddresses.length;i++){ 
      Path inputPath = Paths.get(arrayOfStemmedFileAddresses[i]); 
      String idString=String.format("%05d", (i+1)); 
      String outputPath=frequenceyDocFolderPath+idString+".txt"; 

      // do your counting here 


      writeMapToFile(uniqueTreeSortedMap, idString, outputPath); 
     } 

     System.out.println("Counting is Done");    
    } 

public static void writeMapToFile(Map<String,Integer> map, String idString, String outputPath) throws FileNotFoundException{ 
     PrintWriter writer = new PrintWriter(outputPath); 
     Set s = map.entrySet(); 
     Iterator it = s.iterator(); 
     while (it.hasNext()) { 
      Map.Entry entry = (Map.Entry) it.next(); 
      String key = (String) entry.getKey(); 
      Integer value = (Integer) entry.getValue(); 
      //System.out.println(key + "," + value); 
      writer.println(idString+","+key + "," + value); 
     }//while 
     writer.close(); 
    } 

} 

運行後我得到這些結果在FrequenceyFolder,每個文件的輸出將導致一個單獨的文件。 (每個命名00001.txt00002.txt ...)具有以下格式:


FrequenceyFolder: 00001.txt包括:

00001,aerodynam,2 
00001,agre,3 
00001,angl,1 
00001,attack,7 
00001,basi,4 
.... 

in FrequenceyFolder: 00999.txt包括:

00999,aerodynam,5 
00999,evalu,1 
00999,lift,3 
00999,ratio,2 
00999,result,9 
.... 

FrequenceyFolder: 01400.txt包括:

01400,subtract,1 
01400,support,1 
01400,theoret,1 
01400,theori,1 
01400,..... 

這是我從你的問題的理解。讓我知道。

相關問題