Skip to content

Commit

Permalink
Reuse Files.readAllBytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
garydgregory committed Oct 7, 2024
1 parent 38ae554 commit 7e756e9
Showing 1 changed file with 9 additions and 19 deletions.
28 changes: 9 additions & 19 deletions src/main/java/org/apache/commons/fileupload/disk/DiskFileItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
Expand All @@ -35,6 +37,7 @@
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.function.Uncheck;
import org.apache.commons.io.output.DeferredFileOutputStream;

/**
Expand Down Expand Up @@ -231,12 +234,12 @@ protected void finalize() {
}

/**
* Returns the contents of the file as an array of bytes. If the
* contents of the file were not yet cached in memory, they will be
* loaded from the disk storage and cached.
* Gets the contents of the file as an array of bytes. If the contents of the file were not yet cached in memory, they will be loaded from the disk storage
* and cached.
*
* @return The contents of the file as an array of bytes
* or {@code null} if the data cannot be read
* @return The contents of the file as an array of bytes or {@code null} if the data cannot be read.
* @throws UncheckedIOException if an I/O error occurs.
* @throws OutOfMemoryError if an array of the required size cannot be allocated, for example the file is larger that {@code 2GB}.
*/
@Override
public byte[] get() {
Expand All @@ -246,20 +249,7 @@ public byte[] get() {
}
return cachedContent != null ? cachedContent.clone() : new byte[0];
}

byte[] fileData = new byte[(int) getSize()];
InputStream fis = null;

try {
fis = new FileInputStream(dfos.getFile());
IOUtils.readFully(fis, fileData);
} catch (final IOException e) {
fileData = null;
} finally {
IOUtils.closeQuietly(fis);
}

return fileData;
return Uncheck.get(() -> Files.readAllBytes(dfos.getFile().toPath()));
}

/**
Expand Down

0 comments on commit 7e756e9

Please sign in to comment.