簡體   English   中英

Java讀取文件,如果不存在則創建它

[英]Java read a file, if it doesn't exist create it

這是我的代碼

public String path;
public String fileName;
public static void readData() throws IOException{
    try {
        path="myPath"
        fileName="myFileName";
        fstream = new FileInputStream(path+fileName);
        br = new BufferedReader(new InputStreamReader(fstream));
        //do something...//
        }
        br.close();
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Reading file error");
        Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我想知道如何檢查fstream是否存在。 如果它不存在,則必須創建新文件。 我怎樣才能做到這一點? 謝謝

這是一個可能的解決方案:

public static void readData() throws IOException
{
    File file = new File(path, filename);

    if (!file.isFile() && !file.createNewFile())
    {
        throw new IOException("Error creating new file: " + file.getAbsolutePath());
    }

    BufferedReader r = new BufferedReader(new FileReader(file));

    try 
    {
        // read data
    }finally
    {
        r.close();
    }
}

你的代碼中缺少一些東西 - 有一個沒有相應開口支撐的右括號。

但要回答你的問題,首先創建一個File對象,然后使用exists() ,然后如果exists()返回false則使用createNewFile() File對象而不是文件名傳遞給FileInputStream構造函數。

順便說一句,它會花費你更少的時間去谷歌答案,而不是在這里輸入你的問題。

要檢查path中是否存在文件文件filename ,可以使用new File(path, filename).exists()

如果指定File的文件系統上存在文件或目錄,則exists方法返回true。

要驗證文件是文件而不是目錄,可以使用isFile方法

有關更多信息,請參閱java.io.Filejavadoc

if(new File("filename").exists())
   ...

它應該做你想要的。

您已經捕獲了FileNotFoundException ,這是您知道您想要讀取的文件不存在的地方,您可以創建它。

暫無
暫無

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

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