Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: close resource in ZipFolder.java #2623

Merged
merged 3 commits into from
Oct 9, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions src/main/java/spoon/support/compiler/ZipFolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,19 @@ public List<SpoonFile> getFiles() {
// Indexing content
if (files == null) {
files = new ArrayList<>();
try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {
final int buffer = 2048;
try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
ByteArrayOutputStream output = new ByteArrayOutputStream(buffer)) {
ZipEntry entry;
while ((entry = zipInput.getNextEntry()) != null) {
// deflate in buffer
final int buffer = 2048;
ByteArrayOutputStream output = new ByteArrayOutputStream(buffer);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code seems to be wrong.
The content of output will grow with each zip entry. Before, it was reset with each entry.
Solution:
A) create ByteArrayOutputStream in scope of while body, similar like before
B) call ByteArrayOutputStream#reset() method to clear it's content

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you Pavel. I felt there is something wrong with it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please consider using IOUtils from Apache.

int count;
byte[] data = new byte[buffer];
while ((count = zipInput.read(data, 0, buffer)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();

files.add(new ZipFile(this, entry.getName(), output
.toByteArray()));
files.add(new ZipFile(this, entry.getName(), output.toByteArray()));
}
} catch (Exception e) {
Launcher.LOGGER.error(e.getMessage(), e);
Expand Down