有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Scala apache commons lang3验证的方法?

Scala实现与apache commons lang3Validate相同功能的方法是什么?i、 e.验证的目的是用户输入验证,而不是通过断言编码错误,如果条件不满足,将导致IllegalArgumentException

/**
 * Returns the newly created file only if the user entered a valid path.
 * @param path input path where to store the new file
 * @param fileName name of the file to be created in directory path
 * @throws IllegalArgumentException when the input path doesn't exist.  
 */
public File createFile(File path, String fileName) {
    // make sure that the path exists before creating the file
    // TODO: is there a way to do this in Scala without the need for 3rd party libraries
    org.apache.commons.lang3.Validate.isTrue(path.exists(), "Illegal input path '" + path.getAbsolutePath() + "', it doesn't exist")
    // now it is safe to create the file ...
    File result = new File(path, fileName)
    // ...
    return result;
}

共 (1) 个答案

  1. # 1 楼答案

    巧合的是,我刚刚发现require将是Scala中的首选方法

    /**
     * Returns the newly created file only if the user entered a valid path.
     * @param path input path where to store the new file
     * @param fileName name of the file to be created in directory path
     * @throws IllegalArgumentException when the input path doesn't exist.  
     */
    def createFile(path: File, fileName: String) : File = {
        require(path.exists, s"""Illegal input path "${path.getAbsolutePath()}", it doesn't exist""")
        // now it is safe to create the file ...
        val result = new File(path, fileName)
        // ...
        result
    }