Java – BufferedWriter
Java – BufferedWriter
如果您想使用BufferedWriter
将某些内容写入 Java 中的文件中,请使用以下代码作为模板,并按自己的方式重复使用它。
1)使用不带try-with-resources
的BufferedWriter
(在 Java 7 之前)
package com.howtodoinjava.examples.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample
{
public static void main(String[] args)
{
try {
String content = "Hello Learner !! Welcome to howtodoinjava.com.";
File file = new File("c:/temp/samplefile.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
2)将BufferedWriter
与try-with-resources
结合使用(Java 7 及更高版本)
package com.howtodoinjava.examples.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample
{
public static void main(String[] args)
{
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\temp\\testOut.txt")))
{
String content = "Hello Learner !! Welcome to howtodoinjava.com.";
bufferedWriter.write(content);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果