Java中文件的创建
File file=new File(“text.txt”)
運行這行代碼,我們會發現相應的文件夾下無法找到創建的text.txt
首先 File 類是對文件系統的映射 并不是硬盤上真實的文件
所以 new File("xxx.xxx") 只是在內存中創建File文件映射對象,而并不會在硬盤中創建文件
如果需要創建文件需要以下操作:
判斷映射的文件是否真實存在 file.exists() //true存在 false不存在
如果存在即可直接操作, 否則需要調用 file.createNewFile() 創建真實文件
如何獲取當前的工作目錄?
public class Test1 {
?? ? public static void main(String[] args) {
?? ? ? ? ? ?String curDir = System.getProperty("user.dir");
?? ? ? ? ? ?System.out.println("你當前的工作目錄為 :" + curDir);
?? ? ? ?}
}
建立文件的代碼為:
package java15;
import java.io.File;
public class Demo1 {
?? ?public static void main(String[] args)
?? ?{
?? ??? ?File file = new File("text1.txt");
?? ??? ?if(file.exists())
?? ??? ?{
?? ??? ??? ?file.delete();
?? ??? ??? ?System.out.println("文件已刪除");
?? ??? ?}
?? ??? ?else
?? ??? ?{
?? ??? ??? ?try {
?? ??? ??? ??? ?file.createNewFile();
?? ??? ??? ??? ?System.out.println("文件已創建");
?? ??? ??? ?}catch(Exception e) {
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ??? ?
?? ??? ?}
?? ?}
}
第一次運行時:
會在目錄下建立一個text.txt的文件
?
第二次運行時,文件會被刪除
總結
以上是生活随笔為你收集整理的Java中文件的创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows 程序设计技巧
- 下一篇: Leetcode--7. 整数反转