简体   繁体   中英

Creating and writing to a file with UTF-8 encoding

Here is my Java code.

File file = new File(path);
StringWriter sw = new StringWriter();
//Do something.
out.println(sw.toString()); //Works fine; prints.
try {
        FileUtils.writeStringToFile(file, sw.toString(), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException( e );
    }

I don't already have the file created, and neither is it creating it after the execution. How can I do this?

See File.createNewFile() .

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. ..

As mentioned by @JohnWatts in comments:

..both PrintWriter and your code create the file, but pre-1.3 FileUtils.writeStringToFile does not.

Don't use StringWriter , use PrintWriter instead:

 PrintWriter w = new PrintWriter(file);
 w.print(string);
 w.flush();
 w.close()

I checked the code and it works.

The only problem that I could think of is path value. Try with hardcoded path value. Because I doubt file is getting created and you are not able to find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM