Copying a binary file outside of a jar

时光总嘲笑我的痴心妄想 提交于 2020-01-04 09:37:22

问题


I have an exe packaged inside my jar file and I am trying to copy it to a temporary location so that i can run it using Desktop.browse(), to do this I set up a scanner with the input stream constructor using class.getResourceAsStream, and then with a printwriter wrote that all to a file. The problem that occurred says that the exe is invalid. I think this is due to some binary data being lost. If anyone can help please post a comment.

    Scanner sc = new Scanner(ClassBuilder.class.getResourceAsStream("jd-gui.exe"));
    File copy = new File("C://users//Owner//Desktop//java//jd-gui.exe");
    copy.createNewFile();
    PrintWriter writer = new PrintWriter(copy);

    while(sc.hasNextLine())
        writer.println(sc.nextLine());

    writer.flush();
    writer.close();
    sc.close();

    Desktop.getDesktop().browse(copy.toURI()); 

回答1:


As already mentioned use streams for binary data. Commons io makes copying streams easy. Something like:

InputStream in = getClass().getResourceAsStream("jd-gui.exe");
OutputStream out = new FileOutputStream("jd-gui.exe");
IOUtils.copy(in, out);


来源:https://stackoverflow.com/questions/15558626/copying-a-binary-file-outside-of-a-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!