我是 Java 新生,最近去面试了。他们问了一个类似的问题:设置 Groovy,测试示例 json 文件是否有效。如果有效,则运行 json 文件。如果不是,则打印“文件无效”。如果找不到文件,则打印“找不到文件”。我有 2 小时的时间来做这件事,我可以使用互联网。
由于我不知道 groovy 是什么或 json 是什么,我搜索它并设置了 groovy 但无法在两个小时内获得输出。我应该写什么?我尝试了一些代码,但我确定它是错误的。
最佳答案
您可以使用 file.exists()
检查文件系统上是否存在该文件和 file.canRead()
检查它是否可以被应用程序读取。然后使用 JSONSlurper
解析文件并捕获 JSONException
如果 json 无效:
import groovy.json.*
def filePath = "/tmp/file.json"
def file = new File(filePath)
assert file.exists() : "file not found"
assert file.canRead() : "file cannot be read"
def jsonSlurper = new JsonSlurper()
def object
try {
object = jsonSlurper.parse(file)
} catch (JsonException e) {
println "File is not valid"
throw e
}
println object
要从命令行传递文件路径参数,请替换
def filePath = "/tmp/file.json"
和assert args.size == 1 : "missing file to parse"
def filePath = args[0]
并在命令行执行
groovy parse.groovy /tmp/file.json
关于json - Groovy 文件检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262999/