Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy file check

Tags:

json

groovy

I am a java fresher and I went to an interview recently. They asked a question which was something like: Set up Groovy, test whether a sample json file is valid or not. If it is valid, run the json file. If it is not, print "File is not valid". If file is not found, print "file not found". I was given 2 hours time to do it and I could use the internet.

As I had no idea what groovy was or json was, I searched it and set up groovy but could not obtain the output in two hours. What should I have written? I tried some code but I am sure that it was wrong.

like image 497
krisnis Avatar asked Sep 01 '16 05:09

krisnis


1 Answers

You can use file.exists() to check if the file exists on the filesystem and file.canRead() to check if it can be read by the application. Then use JSONSlurper to parse the file and catch JSONException if the json is invalid:

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

To pass the file path argument from the command line, replace def filePath = "/tmp/file.json" with

assert args.size == 1 : "missing file to parse"
def filePath = args[0]

and execute on the command line groovy parse.groovy /tmp/file.json

like image 171
Gergely Toth Avatar answered Nov 02 '22 03:11

Gergely Toth