Over a million developers have joined DZone.

Replace File In JAR Archive

·
// This is a method I just wrote for my current project. It replaces a file (in this case the content.xml) with a newer version of this file. To do this a new JAR archive is generated, all content (except the file which has to be replaced) of the old file is copied to the new archive, the newer version of the file is added to the archive, the old archive is deleted and the new archive gets the name of the old one. 



/**
	 * Replaces the old content.xml with the modified version after saving.
	 * Copies all content from the JAR file expect the content.xml to a temporary file, adds the
	 * modified content.xml to the temporary file, deletes the old JAR file and renames the temporary 
	 * file with the name of the old JAR file 
	 * @param oldFile contains the presentation before saving
	 * @param newFile an empty temporary file (=the new jar file)
	 * @param f the file which should be added to the new archive (=the new content.xml)
	 */
	public void copyToNewJar(JarFile oldFile, File newFile,File f){
		
		try {
			InputStream jarIs=null;
			FileInputStream fileIs = new FileInputStream(f.getName());
			Enumeration entries = oldFile.entries();
			JarOutputStream newJarOs =new JarOutputStream(new FileOutputStream(newFile.getName()));
			int read;
			byte buffer[] = new byte[1024];
			
			while (entries.hasMoreElements()) {
				JarEntry entry = (JarEntry) entries.nextElement();
				String name = entry.getName();
				System.out.println("name: "+name);
				
				//ignore the old content.xml
				if(name.equals("content.xml")){
					continue;
				}
				 System.out.println(oldFile.getName());
				 jarIs= oldFile.getInputStream(entry);
				 
				 newJarOs.putNextEntry(entry);
			     while ((read = jarIs.read(buffer)) != -1) {
					newJarOs.write(buffer, 0, read);
				 }
			}	
			//add the new content.xml
			JarEntry entry = new JarEntry(f.getName());
			newJarOs.putNextEntry(entry);
			while ((read = fileIs.read(buffer)) != -1) {
				newJarOs.write(buffer, 0, read);
			}
			fileIs.close();
			newJarOs.close();
			if(jarIs!=null){
				jarIs.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//close and delete the old jar file, and rename the temporary file
                try {
			oldFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		File origFile = new File(oldFile.getName());
		origFile.delete();
		newFile.renameTo(origFile);
		
		
	}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}