How to convert a String into a File Object in java?

groovy, java

Solution

As this is Groovy, you can simplify the other two answers with:

File writeToFile( String filename, String content ) {
  new File( filename ).with { f ->
    f.withWriter( 'UTF-8' ) { w ->
      w.write( content )
    }
    f
  }
}

Which will return a file handle to the file it just wrote `content` into

Problem

I have file contents in a java string variable, which I want to convert it into a `File` object is that possible? ``` public void setCfgfile(File cfgfile) { this.cfgfile = cfgfile } public void setCfgfile(String cfgfile) { println "ok overloaded function" this.cfgfile = new File(getStreamFromString(cfgfile)) } private def getStreamFromString(String str) { // convert String into InputStream InputStream is = new ByteArrayInputStream(str.getBytes()) is } ```

Original source