簡體   English   中英

使用正則表達式將文件結尾與目標文件夾中的擴展名war相匹配

[英]Use regex to match file ending with extension war in target folder

我正在嘗試使用正則表達式從目標文件夾中獲取文件。 我正在部署war文件,並且為了運行它我需要確定保存在目標文件夾中的war文件,以便它可以安裝它並運行我的tomcat實例。

我不能提到靜態路徑,因為我的戰爭版本會在發布之后發生變化。 我不想每次都手動更新它。

我使用了以下正則表達式,但這似乎不起作用。

Matcher matcher = Pattern.compile("(.+?)(\\.war)$").matcher("./target/");
webapp = new File(matcher.group(1));

我希望獲取目標文件夾中存在的war文件。

我還可以將兩個不同的匹配器("./target/" or ./nameOfComponent/target/")附加到單個模式中嗎?

迭代文件,檢查每個文件的模式。

// only needed once for all files
Pattern pattern = Pattern.compile("(.+?)(\\.war)$");

// collect all files in all relevant directories
List<File> potentialFiles = new ArrayList<>();
potentialFiles.addAll(Arrays.asList(new File("./target/").listFiles()));
potentialFiles.addAll(Arrays.asList(new File("./nameOfComponent/target/").listFiles()));

File webapp = null;
for (File file : potentialFiles) {
    Matcher matcher = pattern.matcher(file.getName());
    if (matcher.matches()) {
        webapp = file;
        break; // use this line if you only want the first match
    }
}

// use "webapp", but expect null if there was no match

你可以這樣做:

    File dir = new File("directory/path");
    File[] all = dir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".war");
        }
    });

這將獲得包含“directory / path”文件夾中所有“.war”文件的File[]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM