我是一名
java新手,最近我去了一个采访.他们问了一个类似的问题:设置Groovy,测试样本json文件是否有效.如果有效,请运行json文件.如果不是,请打印“文件无效”.如果找不到文件,请打印“找不到文件”.我有2个小时的时间去做,我可以使用互联网.
由于我不知道groovy是什么或json是什么,我搜索它并设置groovy但无法在两小时内获得输出.我该怎么写?我尝试了一些代码,但我确信这是错误的.
解决方法
您可以使用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