我正在使用从SourceForge下载的一些Java代码。我有源代码,但是用户被引导通过jar文件运行代码:
java -jar jarfile.jar -i inputfile.txt -o $outputdirectory
自然地,我可以jarfile.jar
使用以下命令查看其中的内容,
jar tf jarfile.jar
这是我的问题:我想在源代码中进行一些更改,然后再运行。我该怎么做呢?用户通常
(1)在jarfile.jar中更改已编译的Java代码?听起来像是一团糟
(2)再次将源代码包装到jar文件中?
我将如何获取源代码(已进行更改)并创建一个新.jar
文件?
在此处找到以下代码以提取JAR内容:
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.ZipException;
public class jara {
public static void main (String args[])throws IOException,ZipException
{
JarFile jarFile = new JarFile("jarfile.jar");
Enumeration en = jarFile.entries();
while (en.hasMoreElements()) {
String ent=proc(en.nextElement());
if(ent.indexOf("/")>0)
{
String fil=ent.substring(0,ent.indexOf("/"));
System.out.println(fil);
File local=new File(fil);
if(!local.exists())
local.mkdirs();
}
if(ent.indexOf(".")>0)
{
int n=ent.length();
String fil1=ent.substring(ent.lastIndexOf("/")+1,n);
System.out.println(fil1);
extract(jarFile.getName(),ent);
}
}
}
public static String proc(Object obj)
{
JarEntry entry = (JarEntry)obj;
String name = entry.getName();
System.out.println("\nEntry Name: "+name);
return(name);
}
public static void extract(String jarName,String entryName)throws IOException,ZipException
{
JarFile jar = new JarFile(jarName);
System.out.println(jarName + " opened.");
try {
// Get the entry and its input stream.
JarEntry entry = jar.getJarEntry(entryName);
// If the entry is not null, extract it. Otherwise, print a
// message.
if (entry != null) {
// Get an input stream for the entry.
InputStream entryStream = jar.getInputStream(entry);
try {
// Create the output file (clobbering the file if it exists).
FileOutputStream file = new FileOutputStream(entry.getName());
try {
// Allocate a buffer for reading the entry data.
byte[] buffer = new byte[1024];
int bytesRead;
// Read the entry data and write it to the output file.
while ((bytesRead = entryStream.read(buffer)) != -1) {
file.write(buffer, 0, bytesRead);
}
System.out.println(entry.getName() + " extracted.");
}
finally {
file.close();
}
}
finally {
entryStream.close();
}
}
else {
System.out.println(entryName + " not found.");
} // end if
}
finally {
jar.close();
System.out.println(jarName + " closed.");
}
}
}
然后,只需读取Java源文件,就好像它们是文本文件一样,对其进行修改,然后将其写入新文件。
然后,要打包jar,可以使用本教程,该教程使用Java Compiler API。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句