2012-10-27 86 views

回答

1

在Java中輕鬆完成

File counterFile = new File("countervalue.txt"); 
counterFile.createNewFile(); 
2

的基本方法來創建該文件將調用File#createNewFile方法:現在

File counterFile = new File("countervalue.txt"); 
try { 
    counterFile.createNewFile(); 
} catch (Exception e) { 
    System.out.println("File couldn't been created."); 
} 

,如果你想創建一個新的文件,並填寫它數據,您可以使用FileWriterPrintWriter作爲文本文件(假設這適用於您示例中的txt擴展名):

File counterFile = new File("countervalue.txt"); 
PrintWriter pw = null; 
try { 
    //it will automatically create the file 
    pw = new PrintWriter(new FileWriter(counterFile)); 
    pw.println("Hello world!"); 
} catch (Exception e) { 
    System.out.println("File couldn't been created."); 
} finally { 
    if (pw != null) { 
     pw.flush(); 
     pw.close(); 
    } 
} 

如果你想只將數據添加到您的文件,使用FileWriter(File, boolean)構造函數傳遞true作爲第二個參數:(!f.exists())

pw = new PrintWriter(new FileWriter(counterFile, true)); 
相關問題