使用模式匹配器为 File.separator 创建函数

问题描述 投票:0回答:2

在我的 java 项目上运行时,静态分析工具给出“文件分隔符中的可移植性缺陷”错误,我需要修复它。在我的代码中,我有 fileUnsafe。我想用一种方法将其转换为fileSafe(下面解释)。

// Case 1
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");

//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

类似的路径 -

// Case 2
//no platform independence, good for Unix systems
File fileUnsafe = new File("/tmp/abc.txt");

// platform independent and safe to use across Unix and Windows
File fileSafe = new File(File.separator+"tmp"+File.separator+"abc.txt");

我的项目中有多个这样的文件地址,我需要创建一些转换方法,该方法可以将此路径作为字符串,将 File.separator 附加到它,然后返回它。像这样的东西-

File fileSafe = new File(someConversionMethod("/tmp/abc.txt"));

我尝试了这个方法,但在情况 2 上它给了我 NullPointerException。

public static String someConversionMethod(String target) {
        Pattern ptr = Pattern.compile("[\\\\\\\\|/]+");
        Matcher mtr = ptr.matcher(target);
        return mtr.replaceAll(File.separator + "" + File.separator);
    }

任何修复此方法或建议一种优雅的方式来处理这种情况的帮助将不胜感激。

nit - 我提到了使用 java.regex Pattern Matcher 用 File.separator 替换字符,但它并没有真正帮助我的情况。

java regex separator
2个回答
0
投票

我会尝试将文件分隔符处的字符串拆分为一个数组,如下所示。

String str = "/tmp/abc.txt";
String result = "";
String rgx = "\\\\|/";
String [] arrOfStr = str.split(rgx);;

然后您可以使用 for 循环将

File.separator
添加回来。像这样:

    for (int i = 1; i < arrOfStr.length ; i++)
        result += File.separator + arrOfStr[i];

我从索引一开始,因为第一个斜杠在结果字符串中加倍。


0
投票

由于这是一次性更改,您可以在 Eclipse 中使用正则表达式查找和替换

对于第一种情况: 使用正则表达式:

^File\sfileUnsafe\s=\snew File\(\"(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);

替换为:

File fileSafe = new File("${folder1}"+File.separator+"${fileName}${extension}");

演示

对于第二种情况: 使用正则表达式:

^File\sfileUnsafe\s=\snew File\(\"\/(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);

替换为:

File fileSafe = new File(File.separator+"${folder1}"+File.separator+"${fileName}${extension}");

演示

如果您有多个文件夹,您可以继续此模式并修复它们。

我承认,这不是一个干净直接的方法,但可以完成工作。

© www.soinside.com 2019 - 2024. All rights reserved.