Here are twoJava FileWriter examples showing that: Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file Writer fileWriter = new FileWriter("c:\\data\\output.txt", ...
What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
解决方案
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
importjava.io.File; importjava.io.FileOutputStream; importjava.io.*; public class tt { public tt() { } public static void main(String[] args) { FileOutputStream out =null; FileOutputStream
import java.io.File;
import java.io.FileOutputStream;
import java.io.*;
public class tt {
public tt() {
}
public static void main(String[] args) {
FileOutputStream out =null;
FileOutputStream outSTr =null;
BufferedOutputStream Buff =null;
FileWriter fw =null;
int count = 1000;// 写文件行数
try{
out =new FileOutputStream(new File("C:/add.txt"));
long begin = System.currentTimeMillis();
for(int i = 0; i