Hey guys, I'm not entirely new to java, but how it handles jar files puzzles me a bit. I want to be able to back up an already existing jar file (which I have working great), then detect and add all of the class files I have in my program's jar into the other jar, and finally delete a specific folder in the other jar. How may I do this?
(This is what I have so far):
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class Patcher
{
public static void main(String[] args)
{
File minecraftJar=new File(System.getenv("APPDATA")+"/.minecraft/bin/minecraft.jar");
File backup=new File(System.getenv("APPDATA")+"/.minecraft/bin/minecraft.backup");
File[] test={new File("config.txt")};
try
{
backup.createNewFile();
copy(minecraftJar,backup);
addFiles(minecraftJar,test);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void copy(File src, File dst) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static void addFiles(File zipFile,File[] files) throws IOException
{
File tempFile = File.createTempFile(zipFile.getName(), null);
tempFile.delete();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null)
{
String name = entry.getName();
boolean notInFiles = true;
for (File f : files)
{
if (f.getName().equals(name))
{
notInFiles = false;
break;
}
}
if (notInFiles)
{
out.putNextEntry(new ZipEntry(name));
int len;
//The line below is where java gives me an EOFException
while ((len = zin.read(buf)) > 0)
{
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
zin.close();
for (int i = 0; i < files.length; i++)
{
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(files[i].getName()));
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
tempFile.delete();
}
}