java 使用 UTF-8 编码创建和写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12262329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating and writing to a file with UTF-8 encoding
提问by Kraken
Here is my Java code.
这是我的 Java 代码。
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?
我还没有创建文件,也没有在执行后创建它。我怎样才能做到这一点?
回答by Andrew Thompson
See File.createNewFile()
.
Atomically creates a new, empty filenamed by this abstract pathname if and only if a file with this name does not yet exist. ..
当且仅当具有此名称的文件尚不存在时,以原子方式创建以该抽象路径名命名的新的空文件。..
As mentioned by @JohnWatts in comments:
正如@JohnWatts 在评论中提到的:
..both
PrintWriter
and your code create the file, but pre-1.3FileUtils.writeStringToFile
does not.
..both
PrintWriter
和您的代码都会创建文件,但 1.3 之前的版本FileUtils.writeStringToFile
不会。
回答by jdevelop
Don't use StringWriter
, use PrintWriter
instead:
不要使用StringWriter
,PrintWriter
而是使用:
PrintWriter w = new PrintWriter(file);
w.print(string);
w.flush();
w.close()
回答by Amit Deshpande
I checked the code and it works.
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.
我能想到的唯一问题是path
价值。尝试使用硬编码的路径值。因为我怀疑文件正在创建并且您无法找到它。