-
江户川乱折腾
创建文本文件:PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");writer.println("The first line");writer.println("The second line");writer.close();创建二进制文件:byte data[] = ...FileOutputStream out = new FileOutputStream("the-file-name");out.write(data);out.close();Java 7+用户可以使用Files该类写入文件:创建文本文件:List<String> lines = Arrays.asList("The first line", "The second line");Path file = Paths.get("the-file-name.txt");Files.write(file, lines, Charset.forName("UTF-8"));//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);创建二进制文件:byte data[] = ...Path file = Paths.get("the-file-name");Files.write(file, data);//Files.write(file, data, StandardOpenOption.APPEND);
-
一只萌萌小番薯
在Java 7及更高版本中:try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");}但是有一些有用的实用程序:来自commons-io的FileUtils.writeStringtoFile(..)来自番石榴的Files.write(..)另请注意,您可以使用a FileWriter,但它使用默认编码,这通常是一个坏主意 - 最好明确指定编码。以下是Java 7之前的原始答案Writer writer = null;try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");} catch (IOException ex) {
// Report} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}}另请参阅:读取,写入和创建文件(包括NIO2)。
-
尚方宝剑之说
如果您已经拥有要写入文件的内容(而不是动态生成),则java.nio.file.FilesJava 7中作为本机I / O的一部分添加提供了实现目标的最简单,最有效的方法。基本上创建和写入文件只是一行,而且一个简单的方法调用!以下示例创建并写入6个不同的文件以展示如何使用它:Charset utf8 = StandardCharsets.UTF_8;List<String> lines = Arrays.asList("1st line", "2nd line");byte[] data = {1, 2, 3, 4, 5};try {
Files.write(Paths.get("file1.bin"), data);
Files.write(Paths.get("file2.bin"), data,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.write(Paths.get("file3.txt"), "content".getBytes());
Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
Files.write(Paths.get("file5.txt"), lines, utf8);
Files.write(Paths.get("file6.txt"), lines, utf8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);} catch (IOException e) {
e.printStackTrace();}
-
九州编程
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
output.close();
}
}
}}