如何在Java中将String转换为File对象?

abi*_*964 3 java groovy

我有一个java字符串变量的文件内容,我想把它转换成一个File对象是可能的吗?

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
}
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 7

由于这是Groovy,您可以使用以下内容简化其他两个答案:

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

这将文件句柄返回到它只是写的文件content