我的线程将从jar文件中读取类数据,另一个线程将修改或删除jar文件。首先读取订单然后删除,但它不起作用,看起来在阅读后无法释放资源,我怎么能伸出来?
InputStream is = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
URL res = new URL(**file**);
is = res.openStream();
bis = new BufferedInputStream(is);
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
byte[] b = baos.toByteArray();
baos.close();
bis.close();
is.close();
return b;
} catch (Exception ex) {
throw ex;
}
参数“file”是一个像这样的字符串“jar:file:/// C:/Users/HJ16748/Desktop/test.jar!/com/services/plugin/test/Test.class”
答案 0 :(得分:0)
将一个finally添加到try catch块并关闭其中的资源。让两个线程名称为Read和Modify。
在删除或修改jar添加行之前修改线程。
try{
System.out.println("Waiting for read to finish");
read.thread.join();
}catch(InterruptedException e){
System.out.println("not able to join");//oops catch
}
//codes to delete or modify jar
用read调用的线程是Thread对象
答案 1 :(得分:0)
ZipFile zf = new ZipFile(entry);
file = file.replaceAll("\\\\", "/");
ZipEntry zipEntry = zf.getEntry(file);
BufferedInputStream bis = new BufferedInputStream(zf.getInputStream(zipEntry));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
b = baos.toByteArray();
baos.close();
bis.close();
zf.close();