抛出文件未找到例外

时间:2015-06-26 18:33:11

标签: java android andengine

我在android项目的资源文件夹中创建了一个gfx文件夹。我存储了我将在我的Android游戏中使用的图像。由于我需要传递图像高度和图像宽度,将其转换为最接近2和inEngine的最高粉末,所以我创建了一个ImageUtility类来读取gfx文件夹中的图像并获得其高度和宽度。

package org.ujjwal.androidGameUtility;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;


public class ImageUtilities {
    private static final String ABSOLUTE_PATH = "F:\\Games\\TowerOfHanoi\\assets\\gfx\\";
    private String fileName = "";
    private File imageFile;
    private int imageHeight;
    private int imageWidth;

    public ImageUtilities(String filename){

        this.fileName = filename;
        this.imageFile = new File(ABSOLUTE_PATH + this.fileName);

        try {
            processImage();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * this methods set the doucment relative path for the graphics to be used
     * and it is mandotry to call before using ImageUtilties object else it will throw filenotFoundException
     * 
     * @param path
     */ 

    private void  processImage() throws FileNotFoundException{
        if(imageFile.exists()){
            try {
                BufferedImage image = ImageIO.read(this.imageFile);
                this.imageWidth = image.getWidth();
                this.imageHeight = image.getHeight();


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                }

            } else{
             throw new FileNotFoundException("Either you missed typed filename or haven't called setAssetBasePathMethod setImageBasePath(String path) method");
        }
    }

    public int getImageHeight(){
        return this.imageHeight;
    }
    public int getImageWidth(){
        return this.imageWidth;
    }

    public String getFileName(){
        return this.fileName;
    }

    public File getImageFile(){
        return this.imageFile;
    }
}

我总是得到FileNotFoundException并带有上面的错误消息。奇怪的问题是当我从其他java类访问图像文件时,我没有收到任何错误。我打印的高度和宽度都完全是我想要但我无法从我的Android游戏项目访问相同的图像文件。这是一个什么样的错误。我为图像提供了绝对文件路径。我还尝试比较它们相同的文件路径。请告诉我我得到了什么错误,我花了一整天时间想弄清楚但是......

1 个答案:

答案 0 :(得分:0)

@mittmemo提到的是正确的,您无法通过手机或模拟器访问F驱动器。你的电脑和android是两个不同的操作系统。您可以做的不是将文件放在/ assets中,而是将其放在/ raw目录下。然后,您可以使用以下方式访问它:

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }