1

Java throws an exception when reading image file:

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)

The image IO works fine while running as Java application:

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);

2 Answers 2

3

that is how it is supposed to work. An applet can't access local files. You might need a signed applet with granted access to the file system.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Would file chooser be able to build the connection by the way?
0

This is expected.

If a Java applet had free access to all local files, imagine how easy it would be to attack someone's local machine. You can use java.io.File to read a file when you are writing a Java application. But if you are writing a Java applet, you have to package the input file as part of your jar and access the file as a "resource":

In order to solve this problem, you will need to use the following method:

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

or

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

It is very easy to do and a quick explanation and usage of this can be found here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.