63

デスクトップアプリケーションとして実行されている別のjarから、jarファイル内のXMLファイルにアクセスしようとしています。必要なファイルのURLを取得できますが、それをFileReaderに(文字列として)渡すと、「ファイル名、ディレクトリ名、またはボリュームラベルの構文が正しくありません」というFileNotFoundExceptionが発生します。

参考までに、同じjarから画像リソースを読み取り、URLをImageIconコンストラクターに渡すことに問題はありません。これは、URLを取得するために使用している方法が正しいことを示しているようです。

URL url = getClass().getResource("/xxx/xxx/xxx/services.xml");
ServicesLoader jsl = new ServicesLoader( url.toString() );

私が持っているServicesLoaderクラスの中に

XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler( this );
xr.setErrorHandler( this );
xr.parse( new InputSource( new FileReader( filename )));

この手法を使用してXMLファイルを読み取ることの何が問題になっていますか?

4

9 に答える 9

68

使用したいようですjava.lang.Class.getResourceAsStream(String)。を参照してください。

https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-

于 2008-12-31T15:52:54.383 に答える
5

これがデスクトップアプリなのかウェブアプリなのかはわかりません。デスクトップの場合は適切なClassLoaderのメソッドを使用しgetResourceAsStream()、Webアプリの場合はContextを使用します。

于 2008-12-31T15:51:39.783 に答える
4

問題は、XMLReader の parse メソッドを呼び出す際に、私がやりすぎたことでした。parse メソッドは InputSource を受け入れるため、FileReader を使用する理由さえありませんでした。上記のコードの最後の行を

xr.parse( new InputSource( filename ));

うまく動作します。

于 2009-02-11T20:38:24.940 に答える
4

結果をコンストラクターURL.toStringの引数として使用しているように見えます。は少し壊れており、代わりに通常は を使用する必要があります。いずれにせよ、文字列はファイル パスではありません。FileReaderURL.toStringurl.toURI().toString()

代わりに、次のいずれかを行う必要があります。

  • URLtoを渡しServicesLoaderて呼び出しさせますopenStream
  • ストリームを使用Class.getResourceAsStreamして渡すだけで、おそらくInputSource. (API は少し複雑なので、忘れずに null をチェックしてください。)
于 2008-12-31T16:00:43.120 に答える
4

問題の 1 つは、同じリソースが複数の jar ファイルにある場合にどうなるかということです。/org/node/foo.txt を読み取りたいとしますが、1 つのファイルからではなく、すべての jar ファイルから読み取りたいとします。

私は以前にこの同じ問題に何度か遭遇しました。私はJDK 7で誰かがクラスパスファイルシステムを書くことを望んでいましたが、残念ながらまだです。

Spring には Resource クラスがあり、クラスパス リソースを非常にうまくロードできます。

複数のjarファイルからリソースを読み取るというまさにこの問題を解決するために、小さなプロトタイプを作成しました。プロトタイプはすべてのエッジ ケースを処理するわけではありませんが、jar ファイル内のディレクトリ内のリソースの検索を処理します。

私はかなり長い間スタックオーバーフローを使用してきました。これは私が質問に答えたことを覚えている 2 番目の回答です。

これはリソース リーダーのプロトタイプです。プロトタイプには、堅牢なエラー チェックがありません。

セットアップした 2 つのプロトタイプ jar ファイルがあります。

 <pre>
         <dependency>
              <groupId>invoke</groupId>
              <artifactId>invoke</artifactId>
              <version>1.0-SNAPSHOT</version>
          </dependency>

          <dependency>
               <groupId>node</groupId>
               <artifactId>node</artifactId>
               <version>1.0-SNAPSHOT</version>
          </dependency>

各 jar ファイルには、/org/node/ の下に resource.txt というファイルがあります。

これは、classpath:// を使用した場合のハンドラーのプロトタイプにすぎません。このプロジェクトのローカル リソースには、resource.foo.txt もあります。

それらをすべてピックアップして印刷します。

   

    package com.foo;

    import java.io.File;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URI;
    import java.net.URL;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

    /**
    * Prototype resource reader.
    * This prototype is devoid of error checking.
    *
    *
    * I have two prototype jar files that I have setup.
    * <pre>
    *             <dependency>
    *                  <groupId>invoke</groupId>
    *                  <artifactId>invoke</artifactId>
    *                  <version>1.0-SNAPSHOT</version>
    *              </dependency>
    *
    *              <dependency>
    *                   <groupId>node</groupId>
    *                   <artifactId>node</artifactId>
    *                   <version>1.0-SNAPSHOT</version>
    *              </dependency>
    * </pre>
    * The jar files each have a file under /org/node/ called resource.txt.
    * <br />
    * This is just a prototype of what a handler would look like with classpath://
    * I also have a resource.foo.txt in my local resources for this project.
    * <br />
    */
    public class ClasspathReader {

        public static void main(String[] args) throws Exception {

            /* This project includes two jar files that each have a resource located
               in /org/node/ called resource.txt.
             */


            /* 
              Name space is just a device I am using to see if a file in a dir
              starts with a name space. Think of namespace like a file extension 
              but it is the start of the file not the end.
            */
            String namespace = "resource";

            //someResource is classpath.
            String someResource = args.length > 0 ? args[0] :
                    //"classpath:///org/node/resource.txt";   It works with files
                    "classpath:///org/node/";                 //It also works with directories

            URI someResourceURI = URI.create(someResource);

            System.out.println("URI of resource = " + someResourceURI);

            someResource = someResourceURI.getPath();

            System.out.println("PATH of resource =" + someResource);

            boolean isDir = !someResource.endsWith(".txt");


            /** Classpath resource can never really start with a starting slash.
             * Logically they do, but in reality you have to strip it.
             * This is a known behavior of classpath resources.
             * It works with a slash unless the resource is in a jar file.
             * Bottom line, by stripping it, it always works.
             */
            if (someResource.startsWith("/")) {
                someResource = someResource.substring(1);
            }

              /* Use the ClassLoader to lookup all resources that have this name.
                 Look for all resources that match the location we are looking for. */
            Enumeration resources = null;

            /* Check the context classloader first. Always use this if available. */
            try {
                resources = 
                    Thread.currentThread().getContextClassLoader().getResources(someResource);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (resources == null || !resources.hasMoreElements()) {
                resources = ClasspathReader.class.getClassLoader().getResources(someResource);
            }

            //Now iterate over the URLs of the resources from the classpath
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();


                /* if the resource is a file, it just means that we can use normal mechanism
                    to scan the directory.
                */
                if (resource.getProtocol().equals("file")) {
                    //if it is a file then we can handle it the normal way.
                    handleFile(resource, namespace);
                    continue;
                }

                System.out.println("Resource " + resource);

               /*

                 Split up the string that looks like this:
                 jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/
                 into
                    this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar
                 and this
                     /org/node/
                */
                String[] split = resource.toString().split(":");
                String[] split2 = split[2].split("!");
                String zipFileName = split2[0];
                String sresource = split2[1];

                System.out.printf("After split zip file name = %s," +
                        " \nresource in zip %s \n", zipFileName, sresource);


                /* Open up the zip file. */
                ZipFile zipFile = new ZipFile(zipFileName);


                /*  Iterate through the entries.  */
                Enumeration entries = zipFile.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    /* If it is a directory, then skip it. */
                    if (entry.isDirectory()) {
                        continue;
                    }

                    String entryName = entry.getName();
                    System.out.printf("zip entry name %s \n", entryName);

                    /* If it does not start with our someResource String
                       then it is not our resource so continue.
                    */
                    if (!entryName.startsWith(someResource)) {
                        continue;
                    }


                    /* the fileName part from the entry name.
                     * where /foo/bar/foo/bee/bar.txt, bar.txt is the file
                     */
                    String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
                    System.out.printf("fileName %s \n", fileName);

                    /* See if the file starts with our namespace and ends with our extension.        
                     */
                    if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) {


                        /* If you found the file, print out 
                           the contents fo the file to System.out.*/
                        try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    //use the entry to see if it's the file '1.txt'
                    //Read from the byte using file.getInputStream(entry)
                }

            }


        }

        /**
         * The file was on the file system not a zip file,
         * this is here for completeness for this example.
         * otherwise.
         *
         * @param resource
         * @param namespace
         * @throws Exception
         */
        private static void handleFile(URL resource, String namespace) throws Exception {
            System.out.println("Handle this resource as a file " + resource);
            URI uri = resource.toURI();
            File file = new File(uri.getPath());


            if (file.isDirectory()) {
                for (File childFile : file.listFiles()) {
                    if (childFile.isDirectory()) {
                        continue;
                    }
                    String fileName = childFile.getName();
                    if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                        try (FileReader reader = new FileReader(childFile)) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }

                }
            } else {
                String fileName = file.getName();
                if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                    try (FileReader reader = new FileReader(file)) {
                        StringBuilder builder = new StringBuilder();
                        int ch = 0;
                        while ((ch = reader.read()) != -1) {
                            builder.append((char) ch);

                        }
                        System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            }
        }

    }


   

サンプル出力を使用して、ここでより完全な例を確認できます。

于 2013-10-13T19:07:57.503 に答える
0

テクニック以外では、標準のJava JarFileクラスを使用して、必要な参照を取得してみませんか?そこからあなたの問題のほとんどはなくなるはずです。

于 2008-12-31T15:51:39.910 に答える
0

リソースを広範囲に使用する場合は、 Commons VFSの使用を検討してください。

以下もサポート: * ローカル ファイル * FTP、SFTP * HTTP および HTTPS * 一時ファイル (通常の FS バックアップ) * Zip、Jar、および Tar (非圧縮、tgz または tbz2) * gzip および bzip2 * リソース * ram - "ramdrive" * mime

JBoss VFSもありますが、あまり文書化されていません。

于 2011-04-10T17:39:16.170 に答える
0

データの読み取りに使用する 2 つの CSV ファイルがあります。Java プログラムは、実行可能な jar ファイルとしてエクスポートされます。それをエクスポートすると、リソースがエクスポートされないことがわかります。

プロジェクトの下に data in eclipse というフォルダーを追加しました。そのフォルダーにcsvファイルを保存しました。

これらのファイルを参照する必要があるときは、次のようにします...

private static final String ZIP_FILE_LOCATION_PRIMARY = "free-zipcode-database-Primary.csv";
private static final String ZIP_FILE_LOCATION = "free-zipcode-database.csv";

private static String getFileLocation(){
    String loc = new File("").getAbsolutePath() + File.separatorChar +
        "data" + File.separatorChar;
    if (usePrimaryZipCodesOnly()){              
        loc = loc.concat(ZIP_FILE_LOCATION_PRIMARY);
    } else {
        loc = loc.concat(ZIP_FILE_LOCATION);
    }
    return loc;
}

次に、jar ファイルをコマンドライン経由で実行できる場所に配置するときは、リソースを含むデータ フォルダーを jar ファイルと同じ場所に追加するようにしてください。

于 2013-08-02T13:40:31.427 に答える