printwriter写入文件_java socket编程

2022-09-22 09:48:29 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

2015-02-20 06:30:01

下面示例代码演示使用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);

}

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/169292.html原文链接:https://javaforall.cn

0 人点赞