2012-08-17 124 views
0

我正在編寫一個程序來從xml文件中獲取存儲過程。我有程序在一個文件上運行。但我需要在多個文件上運行它。問題是我在大目錄中找到正確的xml文件。如何在文件路徑中使用字符串或字符串的子串

例如,路徑可以

C:\ DevStore \ COM \ dev的\存儲\ SQL \ store.xml

C:\存儲\ COM \ dev的\ DevStore \ SQL \ store.xml

等等....

因此,對於上面的例子,我可以有DevStore或商店,在三個可能的位置。

如何使文件路徑在這三個位置使用DevStore或DevStore的任何子字符串?

如果問題不清楚,我很抱歉,我不知道該怎麼說。提前致謝!

+1

和您試過的代碼 – Satya 2012-08-17 04:02:09

+0

您可以定義一個起始點並遞歸遍歷文件夾,搜索xml文件。 – davidbuzatto 2012-08-17 04:02:48

+1

您需要在這些位置查找文件。沒有什麼魔術會爲你做到這一點。 – 2012-08-17 04:03:52

回答

0

下面是一些可以開始工作的代碼。

import java.io.*; 

public class Foo { 

    public static void traverseAndProcess(File startDir) { 
     for (File f : startDir.listFiles()) { 
      // this file is a directory? 
      if (f.isDirectory()) { 
       // yes, it is, so we need to go inside this directory 
       // calling the method again 
       traverseAndProcess(f); 
      } else { 
       // no, it is not a directory 
       // verifies if the file name finishes with ".xml" 
       if (f.getName().lastIndexOf(".xml") != -1) { 
        // it is a xml (just verifying the extension) 
        // so, process this file! 
        process(f); 
       } 
      } 
     } 
    } 

    private static void process(File f) { 
     // here you will process the xml 
     System.out.println("Processing " + f + " file..."); 
    } 

    public static void main(String[] args) { 
     // processing the current directory... change it 
     traverseAndProcess(new File("./")); 
    } 

} 

我的班級設計不是最好的,但正如我所說的,你可以從上面的代碼開始。

0

不,你不能在File路徑中使用通配符,但這個「車輪」已經被髮明瞭...

使用Apache commons-io libraryFileUtils.listFiles()方法,這將遞歸從目錄中獲取所有匹配的文件,在這種情況下C:\(即new File("/")

你必須做一些過濾,並運行它會說明爲什麼你不應該儲存項目直接在根驅動器下 - 總是把他們C:\Projects或類似之下,那麼你就贏了」在尋找某些項目文件時,不得不掃描gazillion窗口文件。

相關問題