How to convert a String to a File object in java?

I have the contents of a file in a java string variable that I want to convert to an object File, what is 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
}
+3
source share
4 answers

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

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

Which will return the file descriptor to the file that he just wrote contentin

+7
source

Try using apache commons io lib

org.apache.commons.io.FileUtils.writeStringToFile(File file, String data)
+2
source

File String File(String). , File ; .

, , , , , :

try {
    Writer f = new FileWriter(nameOfFile);
    f.write(stringToWrite);
    f.close();
} catch (IOException e) {
    // unable to write file, maybe the disk is full?
    // you should log the exception but printStackTrace is better than nothing
    e.printStackTrace();
}

FileWriter , . , , FileOutputStream OutputStreamWriter. :

String encoding = "UTF-8";
Writer f = new OutputStreamWriter(new FileOutputStream(nameOfFile), encoding);
0

String , BufferedWriter:

private writeToFile(String content) {
    BufferedWriter bw;
    try {
        bw = new BufferedWriter(new FileWriter(this.cfgfile));
        bw.write(content);
     }
    catch(IOException e) {
       // Handle the exception
    }
    finally {   
        if(bw != null) {
            bw.close();
        }
    }
}

, new File(filename) File filename ( ). :

this.cfgfile = new File(getStreamFromString(cfgfile))

File String, this.cfgfile = new File(getStreamFromString.

0

All Articles