Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy write out the list to a file

Tags:

groovy

File lstFile = new File(lstFileName).withWriter{out->
            archivedFiles.each {out.println it.name}
}

archivedFiles is a List objects .. I am getting an error that says:

Cannot cast object with class 'java.util.ArrayList' to class 'java.io.File'.

I am only interested in writing out file names contained in the list to the NEWLY created file

like image 709
Phoenix Avatar asked Nov 04 '11 15:11

Phoenix


People also ask

How do I add a list to Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.

How do I set the path of a file in Groovy?

Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used.

How do I print Groovy messages?

You can print the current value of a variable with the println function.


1 Answers

That's beacuse the withWriter block is returning the last thing in the block by default (which is the archivedFiles list)

To do what you're trying to do, you'd need to do:

File lstFile = new File(lstFileName)
lstFile.withWriter{ out ->
  archivedFiles.each {out.println it.name}
}

or this should work too:

File lstFile = new File( lstFileName ).with { file ->
  file.withWriter{ out ->
    archivedFiles.each {out.println it.name}
  }
  file
}
like image 53
tim_yates Avatar answered Sep 22 '22 21:09

tim_yates