Groovy文件检查

时间:2016-09-01 05:02:21

标签: json groovy

我是一名java新手,最近我去了一个采访。他们问了一个类似的问题:设置Groovy,测试样本json文件是否有效。如果有效,请运行json文件。如果不是,请打印“文件无效”。如果找不到文件,请打印“找不到文件”。我有2个小时的时间去做,我可以使用互联网。

由于我不知道groovy是什么或json是什么,我搜索它并设置groovy但无法在两小时内获得输出。我该怎么写?我尝试了一些代码,但我确信这是错误的。

1 个答案:

答案 0 :(得分:16)

您可以使用file.exists()检查文件系统上是否存在该文件,并file.readable()检查该应用程序是否可以读取该文件。然后使用JSONSlurper解析文件,如果json无效,则捕获JSONException

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

上执行