2012-04-08 61 views
0

我已经创建了应显示位于/src/files/pattern.xml中的文件“pattern.xml”的项目。Java Eclipse,导出jar。使用导入的文件

当我在eclipse中运行代码时,它工作正常。但是,当我将项目导出到可执行jar并尝试执行它时,jar不起作用。

也许问题在这里?

URL dir_url = this.getClass().getClassLoader() 
       .getResource("files\\pattern.xml"); 

这里是代码。有任何想法吗?在Eclipse

public class ResourseClass { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    test t = new test(); 
    t.Go(); 
    } 
} 

class test { 

void Go() { 
    try { 

     URL dir_url = this.getClass().getClassLoader() 
       .getResource("files\\pattern.xml"); 
     File dir = new File(dir_url.toURI()); 
     if (dir.exists()) { 
      System.out.println("file exists"); 
     } 

     FileReader frI = new FileReader(dir); 
     BufferedReader br = new BufferedReader(frI); 
     String text; 
     String textout = ""; 

     while ((text = br.readLine()) != null) { 
      textout = textout + text + "\n"; 
     } 

     JOptionPane.showMessageDialog(null, textout, "Information", 
       JOptionPane.WARNING_MESSAGE); 
     br.close(); 

    } catch (FileNotFoundException e2) { 
     // TODO Auto-generated catch block 
     e2.printStackTrace(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } catch (URISyntaxException e3) { 
     // TODO Auto-generated catch block 
     e3.printStackTrace(); 
    } 
} 

    } 

包窗口

enter image description here

正常执行

enter image description here

当代码在eclipse它的工作原理是执行。

+0

我不完全确定它被编译到jar中。你能否检查文件是否存在于.jar文件中? – 2012-04-08 16:39:39

+0

是的,当我打开存档时,文件“pattern.xml”位于.jar存档中。 – 2012-04-08 20:22:36

+0

不应该在.jar/files /中?尝试在jar中创建一个文件夹,移动xml并运行jar。 – 2012-04-08 20:39:14

回答

0

当您在eclipse外部运行pattern.xml文件时,您需要将pattern.xml文件移动到您的类文件所在的文件夹中。