java怎么写文件
1、首先创建一个FileWriter对象;
2、然后使用FileWriter的write方法写入数据;
3、最后使用FileWriter的close方法关闭即可。import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class fileTest {
public static void main(String[] args) {
File file = new File("F:\\test.txt");
if (!file.exists()) {
try {
file.createNewFile(); //如果文件不存在则创建文件
} catch (IOException e) {
e.printStackTrace();
}
}
writeInFile(file, "test"); //写入文件
}
private static void writeInFile(File file, String content) {
Writer writer = null;
StringBuilder outputString = new StringBuilder();
try {
outputString.append(content + "\r\n");
writer = new FileWriter(file, true); // true表示追加
writer.write(outputString.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}