簡體   English   中英

在java中檢查現有文件是否為空

[英]Checking existing file empty or not in java

我的代碼列出 .ncat 文件並將它們打印到屏幕上。 如果目錄中沒有 .ncat 文件,我想打印,它會打印出“沒有 .ncat 文件”我該怎么做?

enter code here

            File f = null;
            String[] paths;

            try{      
                f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");

                paths = f.list();

                for(String path:paths)
                {
                    if(path.toLowerCase().endsWith(".ncat")){
                        System.out.println(path);
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }

文件有一個exists() 方法。 你可以檢查

(new File(path)).exists()

一個非常簡單明了的方法是設置一個標志來指示是否找到了.ncat文件。 如果目錄中沒有.ncat ,則該標志將保持為 false,並且將打印該語句。 請嘗試以下操作:

        File f = null;
        String[] paths;
        boolean fileFound = false;
        try{      
            f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");

            paths = f.list();

            for(String path:paths)
            {
                if(path.toLowerCase().endsWith(".ncat")){
                    System.out.println(path);
                    fileFound = true;

                }
            }
            if (!fileFound) System.out.println("There are no .ncat files");
        }catch(Exception e){
            e.printStackTrace();
        }

您可以使用緩沖區讀取器類:

BufferedReader br = new BufferedReader(new FileReader("pathToFile"));     
if (br.readLine() == null) {
    System.out.println("File is empty");
}

在java中檢查現有文件是否為空

檢查文件是否為

if(new File(pathname).length() > 0)

檢查文件是否存在

if(new File(pathname).exists())

要檢查文件夾及其所有子目錄中是否存在文件,可以遞歸檢查文件夾。

int numberOfFiles = new File(path).listFiles().length;

if(numberOfFiles == 0) {
  System.out.println("Empty Directory");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM