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

Replace FileInputStream and FileOutputStream to nio Files #3055

Merged
merged 2 commits into from
May 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 18 additions & 3 deletions brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -98,6 +99,7 @@ public void decodeSourcesSmali(File apkFile, File outDir, String filename, boole
smaliDir = new File(outDir, SMALI_DIRNAME + "_" + filename.substring(0, filename.indexOf(".")));
}
OS.rmdir(smaliDir);
//noinspection ResultOfMethodCallIgnored
smaliDir.mkdirs();
LOGGER.info("Baksmaling " + filename + "...");
DexFile dexFile = SmaliDecoder.decode(apkFile, smaliDir, filename, bakDeb, apiLevel);
Expand Down Expand Up @@ -236,6 +238,7 @@ public void writeOriginalFiles(ExtFile apkFile, File outDir)
LOGGER.info("Copying original files...");
File originalDir = new File(outDir, "original");
if (!originalDir.exists()) {
//noinspection ResultOfMethodCallIgnored
originalDir.mkdirs();
}

Expand Down Expand Up @@ -313,6 +316,7 @@ public void build(ExtFile appDir, File outFile)
outFile = new File(appDir, "dist" + File.separator + (outFileName == null ? "out.apk" : outFileName));
}

//noinspection ResultOfMethodCallIgnored
new File(appDir, APK_DIRNAME).mkdirs();
File manifest = new File(appDir, "AndroidManifest.xml");
File manifestOriginal = new File(appDir, "AndroidManifest.xml.orig");
Expand Down Expand Up @@ -353,6 +357,7 @@ private void buildManifestFile(File appDir, File manifest, File manifestOriginal
if (manifest.isFile() && manifest.exists()) {
try {
if (manifestOriginal.exists()) {
//noinspection ResultOfMethodCallIgnored
manifestOriginal.delete();
}
FileUtils.copyFile(manifest, manifestOriginal);
Expand Down Expand Up @@ -412,7 +417,7 @@ public boolean buildSourcesRaw(File appDir, String filename)
if (buildOptions.forceBuildAll || isModified(working, stored)) {
LOGGER.info("Copying " + appDir.toString() + " " + filename + " file...");
try {
BrutIO.copyAndClose(new FileInputStream(working), new FileOutputStream(stored));
BrutIO.copyAndClose(Files.newInputStream(working.toPath()), Files.newOutputStream(stored.toPath()));
return true;
} catch (IOException ex) {
throw new AndrolibException(ex);
Expand All @@ -433,6 +438,7 @@ public boolean buildSourcesSmali(File appDir, String folder, String filename)
}
if (buildOptions.forceBuildAll || isModified(smaliDir, dex)) {
LOGGER.info("Smaling " + folder + " folder into " + filename + "...");
//noinspection ResultOfMethodCallIgnored
dex.delete();
SmaliBuilder.build(smaliDir, dex, buildOptions.forceApi > 0 ? buildOptions.forceApi : mMinSdkVersion);
}
Expand Down Expand Up @@ -503,6 +509,7 @@ public boolean buildResourcesFull(File appDir, UsesFramework usesFramework)
File netSecConfOrig = new File(appDir, "res/xml/network_security_config.xml");
if (netSecConfOrig.exists()) {
LOGGER.info("Replacing existing network_security_config.xml!");
//noinspection ResultOfMethodCallIgnored
netSecConfOrig.delete();
}
ResXmlPatcher.modNetworkSecurityConfig(netSecConfOrig);
Expand All @@ -511,7 +518,9 @@ public boolean buildResourcesFull(File appDir, UsesFramework usesFramework)
}

File apkFile = File.createTempFile("APKTOOL", null);
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
//noinspection ResultOfMethodCallIgnored
resourceFile.delete();

File ninePatch = new File(appDir, "9patch");
Expand Down Expand Up @@ -539,6 +548,7 @@ public boolean buildResourcesFull(File appDir, UsesFramework usesFramework)
}

// delete tmpDir
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
}
return true;
Expand Down Expand Up @@ -576,6 +586,7 @@ public boolean buildManifest(ExtFile appDir, UsesFramework usesFramework)
LOGGER.info("Building AndroidManifest.xml...");

File apkFile = File.createTempFile("APKTOOL", null);
//noinspection ResultOfMethodCallIgnored
apkFile.delete();

File ninePatch = new File(appDir, "9patch");
Expand All @@ -590,6 +601,7 @@ public boolean buildManifest(ExtFile appDir, UsesFramework usesFramework)
Directory tmpDir = new ExtFile(apkFile).getDirectory();
tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES);

//noinspection ResultOfMethodCallIgnored
apkFile.delete();
}
return true;
Expand Down Expand Up @@ -668,7 +680,7 @@ public void buildUnknownFiles(File appDir, File outFile, MetaInfo meta)

try (
ZipFile inputFile = new ZipFile(tempFile);
ZipOutputStream actualOutput = new ZipOutputStream(new FileOutputStream(outFile))
ZipOutputStream actualOutput = new ZipOutputStream(Files.newOutputStream(outFile.toPath()))
) {
copyExistingFiles(inputFile, actualOutput);
copyUnknownFiles(appDir, actualOutput, files);
Expand All @@ -677,6 +689,7 @@ public void buildUnknownFiles(File appDir, File outFile, MetaInfo meta)
}

// Remove our temporary file.
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
Expand Down Expand Up @@ -726,7 +739,7 @@ private void copyUnknownFiles(File appDir, ZipOutputStream outputFile, Map<Strin
newEntry.setMethod(ZipEntry.STORED);
newEntry.setSize(inputFile.length());
newEntry.setCompressedSize(-1);
BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(inputFile));
BufferedInputStream unknownFile = new BufferedInputStream(Files.newInputStream(inputFile.toPath()));
CRC32 crc = BrutIO.calculateCrc(unknownFile);
newEntry.setCrc(crc.getValue());
unknownFile.close();
Expand All @@ -743,10 +756,12 @@ private void copyUnknownFiles(File appDir, ZipOutputStream outputFile, Map<Strin
public void buildApk(File appDir, File outApk) throws AndrolibException {
LOGGER.info("Building apk file...");
if (outApk.exists()) {
//noinspection ResultOfMethodCallIgnored
outApk.delete();
} else {
File outDir = outApk.getParentFile();
if (outDir != null && !outDir.exists()) {
//noinspection ResultOfMethodCallIgnored
outDir.mkdirs();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class SmaliMod {
public static boolean assembleSmaliFile(File smaliFile, DexBuilder dexBuilder, int apiLevel, boolean verboseErrors,
Expand All @@ -36,7 +37,7 @@ public static boolean assembleSmaliFile(File smaliFile, DexBuilder dexBuilder, i
CommonTokenStream tokens;
smaliFlexLexer lexer;

InputStream is = new FileInputStream(smaliFile);
InputStream is = Files.newInputStream(smaliFile.toPath());
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);

lexer = new smaliFlexLexer(reader, apiLevel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.xmlpull.v1.XmlSerializer;

import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;
import java.util.zip.CRC32;
Expand Down Expand Up @@ -185,7 +186,7 @@ public void decodeManifestWithResources(ResTable resTable, ExtFile apkFile, File

attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());

Directory inApk, in = null, out;
Directory inApk, out;
try {
inApk = apkFile.getDirectory();
out = new FileDirectory(outDir);
Expand Down Expand Up @@ -433,7 +434,8 @@ private void aapt2Package(File apkFile, File manifest, File resDir, File rawDir,
if (buildOptions.doNotCompress != null && !customAapt) {
// Use custom -e option to avoid limits on commandline length.
// Can only be used when custom aapt binary is not used.
String extensionsFilePath = createDoNotCompressExtensionsFile(buildOptions).getAbsolutePath();
String extensionsFilePath =
Objects.requireNonNull(createDoNotCompressExtensionsFile(buildOptions)).getAbsolutePath();
cmd.add("-e");
cmd.add(extensionsFilePath);
} else if (buildOptions.doNotCompress != null) {
Expand Down Expand Up @@ -555,7 +557,8 @@ private void aapt1Package(File apkFile, File manifest, File resDir, File rawDir,
if (buildOptions.doNotCompress != null && !customAapt) {
// Use custom -e option to avoid limits on commandline length.
// Can only be used when custom aapt binary is not used.
String extensionsFilePath = createDoNotCompressExtensionsFile(buildOptions).getAbsolutePath();
String extensionsFilePath =
Objects.requireNonNull(createDoNotCompressExtensionsFile(buildOptions)).getAbsolutePath();
cmd.add("-e");
cmd.add(extensionsFilePath);
} else if (buildOptions.doNotCompress != null) {
Expand Down Expand Up @@ -801,7 +804,7 @@ public File getFrameworkApk(int id, String frameTag)

if (id == 1) {
try (InputStream in = getAndroidFrameworkResourcesAsStream();
OutputStream out = new FileOutputStream(apk)) {
OutputStream out = Files.newOutputStream(apk.toPath())) {
IOUtils.copy(in, out);
return apk;
} catch (IOException ex) {
Expand All @@ -822,12 +825,13 @@ public void emptyFrameworkDirectory() throws AndrolibException {
LOGGER.warning("Can't empty framework directory, no file found at: " + apk.getAbsolutePath());
} else {
try {
if (apk.exists() && dir.listFiles().length > 1 && ! buildOptions.forceDeleteFramework) {
if (apk.exists() && Objects.requireNonNull(dir.listFiles()).length > 1 && ! buildOptions.forceDeleteFramework) {
LOGGER.warning("More than default framework detected. Please run command with `--force` parameter to wipe framework directory.");
} else {
for (File file : dir.listFiles()) {
for (File file : Objects.requireNonNull(dir.listFiles())) {
if (file.isFile() && file.getName().endsWith(".apk")) {
LOGGER.info("Removing " + file.getName() + " framework file...");
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
Expand Down Expand Up @@ -879,7 +883,7 @@ public void installFramework(File frameFile, String tag)
+ (tag == null ? "" : '-' + tag)
+ ".apk");

out = new ZipOutputStream(new FileOutputStream(outFile));
out = new ZipOutputStream(Files.newOutputStream(outFile.toPath()));
out.setMethod(ZipOutputStream.STORED);
CRC32 crc = new CRC32();
crc.update(data);
Expand Down Expand Up @@ -919,8 +923,9 @@ public void installFramework(File frameFile, String tag)
public void publicizeResources(File arscFile) throws AndrolibException {
byte[] data = new byte[(int) arscFile.length()];

try(InputStream in = new FileInputStream(arscFile);
OutputStream out = new FileOutputStream(arscFile)) {
try(InputStream in = Files.newInputStream(arscFile.toPath());
OutputStream out = Files.newOutputStream(arscFile.toPath())) {
//noinspection ResultOfMethodCallIgnored
in.read(data);
publicizeResources(data);
out.write(data);
Expand Down Expand Up @@ -1034,7 +1039,7 @@ public void close() throws IOException {

public BuildOptions buildOptions;

public Map<String, String> mResFileMapping = new HashMap();
public Map<String, String> mResFileMapping = new HashMap<>();

// TODO: dirty static hack. I have to refactor decoding mechanisms.
public static boolean sKeepBroken = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public static void modNetworkSecurityConfig(File file)
* build, thus preventing the application from installing. This is from a bug/error
* in AOSP where public resources cannot be part of an authorities attribute within
* a provider tag.
*
* <p>
* This finds any reference and replaces it with the literal value found in the
* res/values/strings.xml file.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
import com.android.tools.smali.dexlib2.writer.builder.DexBuilder;
import com.android.tools.smali.dexlib2.writer.io.FileDataStore;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.logging.Logger;

public class SmaliBuilder {
Expand Down Expand Up @@ -63,7 +63,7 @@ private void build() throws AndrolibException {
private void buildFile(String fileName, DexBuilder dexBuilder)
throws AndrolibException, IOException {
File inFile = new File(mSmaliDir, fileName);
InputStream inStream = new FileInputStream(inFile);
InputStream inStream = Files.newInputStream(inFile.toPath());

if (fileName.endsWith(".smali")) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private DexFile decode() throws AndrolibException {
dexEntry = container.getEntry(mDexFile);
}

// Double check the passed param exists
// Double-check the passed param exists
if (dexEntry == null) {
dexEntry = container.getEntry(container.getDexEntryNames().get(0));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Objects;

/**
* Implementation of XmlSerializer interface from XmlPull V1 API. This
Expand Down Expand Up @@ -106,7 +107,7 @@ public class MXSerializer implements XmlSerializer {
private final boolean checkNamesInterned = false;

private void checkInterning(String name) {
if (namesInterned && name != name.intern()) {
if (namesInterned && !Objects.equals(name, name.intern())) {
throw new IllegalArgumentException("all names passed as arguments must be interned"
+ "when NAMES INTERNED feature is enabled");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public static void cleanFrameworkFile() throws BrutException {

public static byte[] readHeaderOfFile(File file, int size) throws IOException {
byte[] buffer = new byte[size];
InputStream inputStream = new FileInputStream(file);
InputStream inputStream = Files.newInputStream(file.toPath());
if (inputStream.read(buffer) != buffer.length) {
throw new IOException("File size too small for buffer length: " + size);
}
Expand Down
1 change: 1 addition & 0 deletions brut.j.dir/src/main/java/brut/directory/DirUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public static void copyToDir(Directory in, File out, String fileName)
} else {
String cleanedFilename = BrutIO.sanitizeUnknownFile(out, fileName);
File outFile = new File(out, cleanedFilename);
//noinspection ResultOfMethodCallIgnored
outFile.getParentFile().mkdirs();
BrutIO.copyAndClose(in.getFileInput(fileName), Files.newOutputStream(outFile.toPath()));
}
Expand Down
2 changes: 2 additions & 0 deletions brut.j.dir/src/main/java/brut/directory/FileDirectory.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public long getCompressedSize(String fileName)
@Override
protected AbstractDirectory createDirLocal(String name) throws DirectoryException {
File dir = new File(generatePath(name));
//noinspection ResultOfMethodCallIgnored
dir.mkdir();
return new FileDirectory(dir);
}
Expand Down Expand Up @@ -93,6 +94,7 @@ protected void loadFiles() {

@Override
protected void removeFileLocal(String name) {
//noinspection ResultOfMethodCallIgnored
new File(generatePath(name)).delete();
}

Expand Down
5 changes: 3 additions & 2 deletions brut.j.dir/src/main/java/brut/directory/ZipUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.Collection;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
Expand All @@ -39,7 +40,7 @@ public static void zipFolders(final File folder, final File zip, final File asse
throws BrutException, IOException {

mDoNotCompress = doNotCompress;
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zip));
ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zip.toPath()));
zipFolders(folder, zipOutputStream);

// We manually set the assets because we need to retain the folder structure
Expand Down Expand Up @@ -67,7 +68,7 @@ private static void processFolder(final File folder, final ZipOutputStream zipOu
if (mDoNotCompress != null && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
zipEntry.setMethod(ZipEntry.STORED);
zipEntry.setSize(file.length());
BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
BufferedInputStream unknownFile = new BufferedInputStream(Files.newInputStream(file.toPath()));
CRC32 crc = BrutIO.calculateCrc(unknownFile);
zipEntry.setCrc(crc.getValue());
unknownFile.close();
Expand Down
2 changes: 2 additions & 0 deletions brut.j.util/src/main/java/brut/util/AaptManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public static String getAaptExecutionCommand(String aaptPath, File aapt) throws
if (! aaptPath.isEmpty()) {
File aaptFile = new File(aaptPath);
if (aaptFile.canRead() && aaptFile.exists()) {
//noinspection ResultOfMethodCallIgnored
aaptFile.setExecutable(true);
return aaptFile.getPath();
} else {
Expand Down Expand Up @@ -101,6 +102,7 @@ public static int getAaptVersion(File aapt) throws BrutException {
if (!aapt.isFile()) {
throw new BrutException("Could not identify aapt binary as executable.");
}
//noinspection ResultOfMethodCallIgnored
aapt.setExecutable(true);

List<String> cmd = new ArrayList<>();
Expand Down
3 changes: 2 additions & 1 deletion brut.j.util/src/main/java/brut/util/Jar.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
Expand Down Expand Up @@ -51,7 +52,7 @@ public static File extractToTmp(String resourcePath, String tmpPrefix, Class<?>
File fileOut = File.createTempFile(tmpPrefix, suffix + ".tmp");
fileOut.deleteOnExit();

OutputStream out = new FileOutputStream(fileOut);
OutputStream out = Files.newOutputStream(fileOut.toPath());
IOUtils.copy(in, out);
in.close();
out.close();
Expand Down