public class Test { public static void main(String[] args) { String directory="myfile/b"; String filename="a.txt"; //註釋掉的爲方法一 /*File file=new File(directory,filename); if (file.exists()) { System.out.println(file.getAbsolutePath()); System.out.println(file.getName()); }else { file.getParentFile().mkdirs(); try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ //此爲方法二: File file=new File(directory); if (!file.exists()) { file.mkdirs(); } File file2=new File(directory,filename); if (!file2.exists()) { try { file2.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //向指定文件中寫入文字 FileWriter fileWriter; try { fileWriter = new FileWriter("myfile/b/a.txt"); //使用緩衝區比不使用緩衝區效果更好,由於每趟磁盤操做都比內存操做要花費更多時間。 //經過BufferedWriter和FileWriter的鏈接,BufferedWriter能夠暫存一堆數據,而後到滿時再實際寫入磁盤 //這樣就能夠減小對磁盤操做的次數。若是想要強制把緩衝區當即寫入,只要調用writer.flush();這個方法就能夠要求緩衝區立刻把內容寫下去 BufferedWriter bufferedWriter=new BufferedWriter(fileWriter); bufferedWriter.write("this is a.txt"); bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }