使用Pattern Matcher为File.separator创建一个函数

时间:2018-05-16 22:30:03

标签: java regex file separator matcher

在我的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 - 我提到Replacing character with File.separator using java.regex Pattern Matcher,但这对我的情况并没有帮助。

2 个答案:

答案 0 :(得分:0)

我会尝试将文件分隔符处的字符串拆分为这样的数组。

private void InitializeJSONResultWriter()
{
    string methodName = Utils.getCurrentMethod();
    Log("In:  " + methodName);
    if (textWriter == null)
    {
        //textWriter = File.CreateText(ResultsPath);
        FileStream strm = File.Open(ResultsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        TextWriter textWriter = File.CreateText(ResultsPath);

        // ? ugh

        _jsonTextWriter = new JsonTextWriter(textWriter);
    }
}

然后,您可以使用for循环添加String str = "/tmp/abc.txt"; String result = ""; String rgx = "\\\\|/"; String [] arrOfStr = str.split(rgx);; 。像这样:

File.separator

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

答案 1 :(得分:0)

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

对于第一种情况: 使用正则表达式:^File\sfileUnsafe\s=\snew File\(\"(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);

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

Demo

对于第二种情况: 使用正则表达式:^File\sfileUnsafe\s=\snew File\(\"\/(?<folder1>[^\/]+)\/(?<fileName>[^\.]+)(?<extension>\.\w{3})\"\);

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

Demo

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

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