簡體   English   中英

Java IO無法在Java Applet下讀取輸入文件

[英]Java IO Can't Read Input File Under Java Applet

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)

在作為Java應用程序運行時,映像IO工作正常:

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

這是應該如何工作的。 applet無法訪問本地文件。 您可能需要一個已授予文件系統授權訪問權限的簽名小程序。

這是預料之中的。

如果Java applet可以自由訪問所有本地文件,想象一下攻擊某人本地計算機是多么容易。 在編寫Java應用程序時,可以使用java.io.File讀取文件。 但是,如果您正在編寫Java小程序,則必須將輸入文件打包為jar的一部分,並將該文件作為“資源”訪問:

要解決此問題,您需要使用以下方法:

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

要么

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

這很容易做到,可以在這里找到快速解釋和使用方法。

暫無
暫無

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

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