Java中檔案的寫入
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class A {
public static void main(String[] args)throws Exception {
String str="hello world!";//要寫入的內容
File f=new File("d:/hello.txt");//要寫入的檔案以及路徑
if(!f.exists()){//判斷檔案是否存在
System.out.println("檔案不存在,正在建立...");
if(f.createNewFile()){//建立檔案
System.out.println("建立成功!");
OutputStream os=new FileOutputStream(f);
BufferedOutputStream bos=new BufferedOutputStream(os);
byte[] bs=str.getBytes();
bos.write(bs);//寫
bos.close();//關閉流
os.close();
System.out.println("完成");
}else{
System.out.println("建立失敗");
}
}else{
System.out.println("檔案已存在,正在刪除...");
if (f.delete()) {
System.out.println("刪除成功");
} else {
System.out.println("刪除失敗");
}
}
}
}