0
public static void writeFile(String theFileName, String theFilePath)
{
    try {
        File currentFile = new File("plugins/mcMMO/Resources/"+theFilePath+theFileName);
        //System.out.println(theFileName);
        @SuppressWarnings("static-access")
        JarFile jar = new JarFile(plugin.mcmmo);
        JarEntry entry = jar.getJarEntry("resources/"+theFileName);
        InputStream is = jar.getInputStream(entry);
        byte[] buf = new byte[(int)entry.getSize()];
        is.read(buf, 0, buf.length);
        FileOutputStream os = new FileOutputStream(currentFile);
        os.write(buf);
        os.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Alright so in my program I have various resources kept within the Jar of the program, when the program runs it has specific files passed to this function that are written to the HDD of the users computer. Everything gets written, but only the images come out 100% correct. The sound files are not so lucky.

Basically, I CANNOT get the sounds to write correctly, their file sizes are correct but they only contain a split second of audio instead of their full length audio. Am I missing something here? I seem to have done everything right, but if that was true I wouldn't be posting here.

I tried my best at googling this problem but it has failed me.

Any guess as to why this doesn't work would be AMAZING!! :)

4

1 回答 1

0

作为JarEntryextends ZipEntry,我建议不要依赖该ZipEntry.getSize()方法,因为它返回 -1。请参阅文档

此外,通常更常见的是在读取流时利用缓冲。在您的示例中,您将所有内容都放在字节数组中,因此我猜对于大文件,您最终可能会以OutOfMemoryError.

这是我要测试的代码:

public static void writeFile(String theFileName, String theFilePath)
{
    try {
        File currentFile = new File("plugins/mcMMO/Resources/"+theFilePath+theFileName);
        @SuppressWarnings("static-access")
        JarFile jar = new JarFile(plugin.mcmmo);
        JarEntry entry = jar.getJarEntry("resources/"+theFileName);
        InputStream is = jar.getInputStream(entry);
        byte[] buf = new byte[2048];
        int nbRead;
        OutputStream os = new BufferedOutputStream(new FileOutputStream(currentFile));
        while((nbRead = is.read(buf)) != -1) {
            os.write(buf, 0, nbRead);
        }
        os.flush();
        os.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
于 2011-09-06T06:42:02.703 回答