簡體   English   中英

Android Studio-編輯器中的FileNotFound異常

[英]Android Studio - FileNotFound exception in editor

我什至在點擊“運行”之前在android studio ide中收到此錯誤。

未處理的異常:java.io.FileNotFoundException

與這個班:

(該類中的函數尚未被調用!)

import java.io.*;


public class FileIO
{
public static byte[] readBinaryFileFromAssets(File file)
{
    byte[] data = null;

    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(data);
    dis.close();

    return data;
}
}

謝謝。

它困擾着您,因為您尚未處理未找到的潛在文件異常。 用try / catch包圍它或拋出異常。

 public static byte[] readBinaryFileFromAssets(File file)
    {
        byte[] data = null;

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(file));
            dis.readFully(data);
            dis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return data;
    }

注意:您可以通過執行alt + enter調出選項,然后選擇“使用try / catch進行環繞”來自動包圍android studio中try / catch中的塊

這看起來像一個已檢查的異常 如果您查看FileInputStream的Docs,您會看到它拋出FileNotFoundException

將您的代碼放在try/catch塊中以解決此類事件,並且錯誤應消失。 就像是:

try {
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    //etc...
} catch (FileNotFoundException e) {
    //Account for situations where the file can't be found
} 

您有一個未被捕獲的異常。 您需要添加一個try / catch塊或讓該方法引發異常。

    public static byte[] readBinaryFileFromAssets(File file){
    try{    
    byte[] data = null;

        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(data);
        dis.close();

        return data;
    }catch(FileNotFoundException e){
    //TODO something appropriate when the file isn't found
    }
return null;
    }

暫無
暫無

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

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