1

Java在读取图像文件时抛出异常:

javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1275)
at UI.readMatrix(UI.java:27)
at MazeViewControl.init(MazeViewControl.java:45)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:680)

图像 IO 在作为 Java 应用程序运行时工作正常:

public class MazeViewControl extends JApplet {
UI ui;
MazeView view;
Maze maze;
int theme;
int option;
String filename="src/maze0.bmp";

public  void init() {
    ui=new UI();
    maze=new Maze();
        try {
            ui.readMatrix("src/maze0.bmp", maze, 1, 0, 0,0,319,239);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

public class UI {
    public UI(){
        return;
    }
/**
   * read and construct the map from a txt file
   * @param filename
   * @throws IOException 
   */
    public void readMatrix(String filename, Maze m, int theme, int option, int sx, int sy, int ex, int ey) throws IOException{
        /* pre-read the file*/

        //Create file for the source
        File input = new File(filename);
        int rows=0;
        int columns=0;
        //Read the file to a BufferedImage
        // Surround this with try/catch or have your method
        // throw an exception
        System.out.println(filename);
        BufferedImage image = ImageIO.read(input);
4

2 回答 2

3

这就是它应该如何工作的方式。小程序无法访问本地文件。您可能需要一个具有文件系统访问权限的签名小程序。

于 2012-09-27T19:26:05.270 回答
0

这是意料之中的。

如果 Java 小程序可以自由访问所有本地文件,想象一下攻击某人的本地计算机将是多么容易。java.io.File在编写 Java 应用程序时,您可以使用它来读取文件。但是,如果您正在编写 Java 小程序,则必须将输入文件打包为 jar 的一部分,并将文件作为“资源”访问:

为了解决这个问题,您将需要使用以下方法:

YourClass.class.getClassLoader().getResourceAsStream("yourfile.txt")

或者

InputStream inputStream = classLoader.getResourceAsStream("yourfile.txt")

这很容易做到,可以在这里找到快速解释和用法。

于 2012-09-27T19:35:10.223 回答