【问题标题】:Acces file from other project where the source is从源所在的另一个项目访问文件
【发布时间】:2012-04-23 19:37:21
【问题描述】:

我有一个带有 .txt 文件的项目(项目源),我想从其他项目(项目调用者)访问该文件。调用者对源有依赖性。所以调用者应该将源代码视为 .jar。好吧,问题是,我必须访问这个 .jar 才能获取 .txt 文件,但我不能。我试过这样的想法: getClass().getResourceAsStream("classpath:/cc.txt");使用输入流 和 getClass().getResource("cc.txt");带有 URL 对象 但我总是得到一个空值。我读过的所有论坛都谈到了这种访问方式。 如何访问 .jar 文件以获取 .txt 文件? 谢谢大家!!

【问题讨论】:

标签: java


【解决方案1】:

以编程方式提取 ZIP/JAR 文件的内容。假设 jarFile 是要提取的 jar/zip 文件。 destDir 是要提取的路径:

java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enum = jar.entries();
while (enum.hasMoreElements()) 
{
    java.util.jar.JarEntry file = (java.util.jar.JarEntry) enum.nextElement();
    java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
    if (file.isDirectory())  // if its a directory, create it
    {
        f.mkdir();
        continue;
    }
    java.io.InputStream is = jar.getInputStream(file); // get the input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
    while (is.available() > 0)  // write contents of 'is' to 'fos'
    {  
       fos.write(is.read());
    }
    fos.close();
    is.close();
}

the same question can be found here...

【讨论】:

  • 但是,如果我想从 getClass 中使用 getResource() 或 getResourceAsStream() 是不可能的?
猜你喜欢
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 2021-07-31
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
相关资源
最近更新 更多