在java编程中,如何将内容写入文件?
此示例显示如何使用BufferedWriter
的write()
方法来写入文件。
package com.yiibai;
import java.io.*;
public class WriteToFile {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename.txt"));
out.write("This a String write to file.\n");
out.close();
System.out.println("File created and write successfully");
} catch (IOException e) {
}
}
}
执行上述示例代码,将产生以下结果 -
File created and write successfully
示例-2
以下是写入一个文件内容的另一个示例。
package com.yiibai;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile2 {
public static void main(String[] args) {
try {
String content = "Yiibai.com is one the best site in the world";
File file = new File("outfile2.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("All Job Done!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:上面代码需要使用JDK7环境编译后运行。
执行上述示例代码,将产生以下结果 -
All Job Done!