簡體   English   中英

從jar文件訪問文件和圖像

[英]Accessing files and images from jar files

嘗試訪問jar文件中的文件和圖像時遇到了問題。 將該程序制作為jar文件之前,可以按預期工作。 我已經創建了一個使用ClassLoader的Resources文件夾,但是在嘗試運行jar文件時仍然出現命令行錯誤,但是它並不能顯示所有信息。

該類型必須是File,以便databaseReader可以讀取它。

錯誤信息

java.io.FileNotFoundException: file:\C:\Users\Nicholas\IdeaProjects\MirrorMe\out\artifacts\MirrorMe_jar\MirrorMe.jar!\GeoLite2-City.mmdb (The filename, directory name, or volume label syntax is incorrect)
    at java.io.RandomAccessFile.open0(Native Method)
    at java.io.RandomAccessFile.open(Unknown Source)
    at java.io.RandomAccessFile.<init>(Unknown Source)
    at com.maxmind.db.BufferHolder.<init>(BufferHolder.java:19)
    at com.maxmind.db.Reader.<init>(Reader.java:116)
    at com.maxmind.geoip2.DatabaseReader.<init>(DatabaseReader.java:35)
    at com.maxmind.geoip2.DatabaseReader.<init>(DatabaseReader.java:23)
    at com.maxmind.geoip2.DatabaseReader$Builder.build(DatabaseReader.java:129)
    at sample.LocateMyCity.<init>(LocateMyCity.java:60)
    at sample.WeatherToday.getPersonLocationId(WeatherToday.java:102)
    at sample.WeatherToday.<init>(WeatherToday.java:126)
    at sample.Main.start(Main.java:37)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)

完整代碼

public class LocateMyCity {

private String myCityLocation;

private String country;

public String getCountry() {
    return country;
}

public String getmyCityLocation(){
    return myCityLocation;
}

public LocateMyCity() {
    try {


        ClassLoader classLoader = getClass().getClassLoader();
        File database = new File(classLoader.getResource("GeoLite2-City.mmdb").getFile());

        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

        String ip = in.readLine(); //you get the IP as a String
        System.out.println(ip);

        // This creates the DatabaseReader object, which should be reused across
        // lookups.
        DatabaseReader reader = new DatabaseReader.Builder(database).build();

        InetAddress ipAddress = InetAddress.getByName(ip);

        // Replace "city" with the appropriate method for your database, e.g.,
        // "country".
        CityResponse response = reader.city(ipAddress);

        City city = response.getCity();
        System.out.println(city.getName()); // 'Minneapolis'
        this.myCityLocation = city.getName();

        Country country = response.getCountry();
        System.out.println(country.getIsoCode());            // 'GB'
        this.country = country.getIsoCode();

        System.out.println(country.getName());               // 'United Kindom'

    }catch (Exception e){
        e.printStackTrace();
        System.out.println("Tracing IP E");
    }
}
}

內部jar文件 提前致謝。

當您的應用程序捆綁為jar文件時,資源不再是文件,而是歸檔文件中的元素(jar文件)。 對於桌面應用程序,該應用程序通常將在不從存檔中提取這些元素的情況下運行。

如果您的數據庫需要一個實際的文件,而不只是一個可以讀取的流(尤其是如果您需要寫入該文件的流),那么您將無法使用存檔中的資源,而必須使用文件文件系統。

您可以輕松地從存檔中提取資源並將其內容寫入本地文件系統。 具體執行方式的具體細節取決於所需的功能。 例如,如果您要作為應用程序功能的一部分寫入數據庫,並且希望這些更改在下次運行應用程序時繼續存在,則您只想在第一次運行時從存檔中提取資源(或者用戶在稍后階段刪除了文件)。 通常,您可以通過將文件放在用戶的主目錄中來執行此操作。 例如,您可以使用以下方法執行此操作:

Path appDirectory = Paths.get(System.getProperty("user.home"), ".application-name");
Path databaseFile = appDirectory.resolve("GeoList2-City.mmdb");

if (! Files.exists(databaseFile)) {
    try {
        // create the app directory if it doesn't already exist:
        Files.createDirectories(appDirectory);

        InputSteam defaultDatabase = getClass().getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
        Files.copy(defaultDatabase, databaseFile);
    } catch (IOException exc) {
        // handle exception here, e.g. if application can run without db,
        // set flag indicating it must run in non-db mode
        // otherwise this is probably a fatal exception, show message and exit...
        exc.printStackTrace();
    }
}

// ...

DatabaseReader reader = new DatabaseReader.Builder(databaseFile.toFile()).build(); 

如果您每次運行該應用程序都需要一個新的數據庫,則可能會復制到一個臨時文件中,並在應用程序退出時刪除該文件。

暫無
暫無

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

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