簡體   English   中英

Java:如果文件不存在,我無法為文件是否存在創建條件。 為什么?

[英]Java: If file doesn´t exist I can´t create condition for file exist or not. Why?

嗨,這是一個簡單的代碼,用於比較文件夾是否存在。

import java.io.*;

public class myfile {
    public static void main(String args[])
    {

        // Get the file
        File f = new File("file_f.txt");

        // Check if the specified file
        // Exists or not
        if (file_f.exists())
            System.out.println("Exists");
        else
            System.out.println("Does not Exists");
            System.out.println("I would like to run this possibility");
    }
}

但是我需要在文件夾不存在時執行代碼。 但是如果我刪除創建文件夾,它會得到一個錯誤......(在我的代碼中,我需要檢查文件夾是否存在,如果不存在,代碼已經開始執行。)那么如果在某些情況下我該怎么做文件夾不存在?

現在我刪除了創建文件,因為我想運行其他部分...

import java.io.*;

public class myfile {
    public static void main(String args[])
    {

        // Get the file

        //File f = new File("friends.txt");



        // Check if the specified file
        // Exists or not
        if (file_f.exists())
            System.out.println("Exists");
        else
            System.out.println("Does not Exists");
            System.out.println("I would like to run this possibility");
    }
}

錯誤:(14, 13)java:找不到符號符號:變量f位置:類myfile

那么,如果在某些情況下文件夾不存在,我該怎么做呢? 謝謝

此行不會在磁盤(或您使用的任何存儲)上創建文件。

File f = new File("friends.txt");

它只是在 JVM 中創建一個對象,您可以使用它來操作文件。 要真正從頭開始創建文件,您需要圍繞該文件創建一種OutputStream在那里寫入一些內容,然后關閉該流。

此代碼將修復您提到的編譯錯誤,並在文件存在和不存在時演示功能

import java.io.*;

public class FileTester {
    private static void testFile(File f){
         // Check if the specified file
        // Exists or not
        if (f.exists())
            System.out.println(f.getAbsolutePath() + " exists");
        else
            System.out.println(f.getAbsolutePath() + " does not exist");        
    }

    public static void main(String args[])
    {
        // assuming friends.txt already exists in current directory, this
        // will print "friends.txt exists"
        testFile(new File("friends.txt"));
        //assuming otherFile.txt does not already exist in current directory
        // this will print "otherFile.txt does not exist"
        testFile(new File("otherFile.txt"));

    }
}

暫無
暫無

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

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