java使用PrintWriter写文件

2015-02-20 06:30:01 阅读( 1843 )

2558人 收藏本页

标签:Java面试题

下面示例代码演示使用PrintWriter方法写文件。

PrintWriter的构造函数接受FileWriter作为参数。得到PrintWriter实例之后调用其println()方法即可写入字符串。

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

public void writeLinesToFile(String filename,
String[] linesToWrite,
boolean appendToFile) {

PrintWriter pw = null;

try {

if (appendToFile) {

//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));

}
else {

pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));

}

for (int i = 0; i < linesToWrite.length; i++) {

pw.println(linesToWrite[i]);

}
pw.flush();

}
catch (IOException e) {
e.printStackTrace();
}
finally {

//Close the PrintWriter
if (pw != null)
pw.close();

}

}

public static void main(String[] args) {
FileUtil util = new FileUtil();
util.writeLinesToFile("myfile.txt", new String[] {"Line 1",
"Line 2",
"Line 3"}, true);
}
}

下一篇:java使用Tookit类获得剪贴板内容

上一篇:java使用BufferedOutputStream写文件

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题