Groovy文件检查

kri*_*nis 10 groovy json

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

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

Ger*_*oth 21

您可以file.exists()用来检查文件系统上是否存在该文件,并file.canRead()检查该应用程序是否可以读取该文件.然后使用JSONSlurper解析文件并捕获JSONExceptionjson是否无效:

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
Run Code Online (Sandbox Code Playgroud)

要从命令行传递文件路径参数,请替换def filePath = "/tmp/file.json"

assert args.size == 1 : "missing file to parse"
def filePath = args[0]
Run Code Online (Sandbox Code Playgroud)

并在命令行上执行 groovy parse.groovy /tmp/file.json