Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

groovy

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
}
like image 310
AabinGunz Avatar asked Oct 17 '25 18:10

AabinGunz


2 Answers

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

like image 76
tim_yates Avatar answered Oct 21 '25 23:10

tim_yates


Try using the apache commons io lib

org.apache.commons.io.FileUtils.writeStringToFile(File file, String data)
like image 25
pbaris Avatar answered Oct 21 '25 23:10

pbaris