Use try-with-resources.

This commit is contained in:
Isira Seneviratne 2020-11-06 06:16:13 +05:30
parent 8bcf0c6498
commit 95333d37c8
8 changed files with 84 additions and 137 deletions

View File

@ -37,14 +37,12 @@ public final class LicenseFragmentHelper {
@NonNull final License license) {
final StringBuilder licenseContent = new StringBuilder();
final String webViewData;
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(
context.getAssets().open(license.getFilename()), StandardCharsets.UTF_8));
try (BufferedReader in = new BufferedReader(new InputStreamReader(
context.getAssets().open(license.getFilename()), StandardCharsets.UTF_8))) {
String str;
while ((str = in.readLine()) != null) {
licenseContent.append(str);
}
in.close();
// split the HTML file and insert the stylesheet into the HEAD of the file
webViewData = licenseContent.toString().replace("</head>",

View File

@ -212,15 +212,14 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
//checkpoint before export
NewPipeDatabase.checkpoint();
final ZipOutputStream outZip = new ZipOutputStream(
new BufferedOutputStream(
new FileOutputStream(path)));
ZipHelper.addFileToZip(outZip, newpipeDb.getPath(), "newpipe.db");
try (ZipOutputStream outZip = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(path)))) {
ZipHelper.addFileToZip(outZip, newpipeDb.getPath(), "newpipe.db");
saveSharedPreferencesToFile(newpipeSettings);
ZipHelper.addFileToZip(outZip, newpipeSettings.getPath(), "newpipe.settings");
outZip.close();
saveSharedPreferencesToFile(newpipeSettings);
ZipHelper.addFileToZip(outZip, newpipeSettings.getPath(),
"newpipe.settings");
}
Toast.makeText(getContext(), R.string.export_complete_toast, Toast.LENGTH_SHORT)
.show();
@ -230,41 +229,23 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
}
private void saveSharedPreferencesToFile(final File dst) {
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(dst))) {
final SharedPreferences pref
= PreferenceManager.getDefaultSharedPreferences(requireContext());
output.writeObject(pref.getAll());
output.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (final IOException ex) {
ex.printStackTrace();
}
}
}
private void importDatabase(final String filePath) {
// check if file is supported
ZipFile zipFile = null;
try {
zipFile = new ZipFile(filePath);
try (ZipFile zipFile = new ZipFile(filePath)) {
} catch (final IOException ioe) {
Toast.makeText(getContext(), R.string.no_valid_zip_file, Toast.LENGTH_SHORT)
.show();
return;
} finally {
try {
zipFile.close();
} catch (final Exception ignored) {
}
}
try {
@ -312,9 +293,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
}
private void loadSharedPreferences(final File src) {
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(src))) {
final SharedPreferences.Editor prefEdit = PreferenceManager
.getDefaultSharedPreferences(requireContext()).edit();
prefEdit.clear();
@ -338,14 +317,6 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
prefEdit.commit();
} catch (final IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (final IOException ex) {
ex.printStackTrace();
}
}
}

View File

@ -34,7 +34,6 @@ import org.schabi.newpipe.MainActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
@ -106,7 +105,6 @@ public final class StateSaver {
+ "writeRead = [" + writeRead + "]");
}
FileInputStream fileInputStream = null;
try {
Queue<Object> savedObjects
= STATE_OBJECTS_HOLDER.remove(savedState.getPrefixFileSaved());
@ -127,10 +125,12 @@ public final class StateSaver {
return null;
}
fileInputStream = new FileInputStream(file);
final ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
//noinspection unchecked
savedObjects = (Queue<Object>) inputStream.readObject();
try (FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream inputStream = new ObjectInputStream(fileInputStream)) {
//noinspection unchecked
savedObjects = (Queue<Object>) inputStream.readObject();
}
if (savedObjects != null) {
writeRead.readFrom(savedObjects);
}
@ -138,13 +138,6 @@ public final class StateSaver {
return savedState;
} catch (final Exception e) {
Log.e(TAG, "Failed to restore state", e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (final IOException ignored) {
}
}
}
return null;
}
@ -227,7 +220,6 @@ public final class StateSaver {
}
}
FileOutputStream fileOutputStream = null;
try {
File cacheDir = new File(cacheDirPath);
if (!cacheDir.exists()) {
@ -258,19 +250,14 @@ public final class StateSaver {
}
}
fileOutputStream = new FileOutputStream(file);
final ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(savedObjects);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream)) {
outputStream.writeObject(savedObjects);
}
return new SavedState(prefixFileName, file.getAbsolutePath());
} catch (final Exception e) {
Log.e(TAG, "Failed to save state", e);
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (final IOException ignored) { }
}
}
return null;
}

View File

@ -45,15 +45,15 @@ public final class ZipHelper {
public static void addFileToZip(final ZipOutputStream outZip, final String file,
final String name) throws Exception {
final byte[] data = new byte[BUFFER_SIZE];
final FileInputStream fi = new FileInputStream(file);
final BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE);
final ZipEntry entry = new ZipEntry(name);
outZip.putNextEntry(entry);
int count;
while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
outZip.write(data, 0, count);
try (FileInputStream fi = new FileInputStream(file);
BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE)) {
final ZipEntry entry = new ZipEntry(name);
outZip.putNextEntry(entry);
int count;
while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
outZip.write(data, 0, count);
}
}
inputStream.close();
}
/**
@ -68,37 +68,35 @@ public final class ZipHelper {
*/
public static boolean extractFileFromZip(final String filePath, final String file,
final String name) throws Exception {
try (ZipInputStream inZip = new ZipInputStream(new BufferedInputStream(
new FileInputStream(filePath)))) {
final byte[] data = new byte[BUFFER_SIZE];
final ZipInputStream inZip = new ZipInputStream(
new BufferedInputStream(
new FileInputStream(filePath)));
boolean found = false;
final byte[] data = new byte[BUFFER_SIZE];
boolean found = false;
ZipEntry ze;
while ((ze = inZip.getNextEntry()) != null) {
if (ze.getName().equals(name)) {
found = true;
// delete old file first
final File oldFile = new File(file);
if (oldFile.exists()) {
if (!oldFile.delete()) {
throw new Exception("Could not delete " + file);
ZipEntry ze;
while ((ze = inZip.getNextEntry()) != null) {
if (ze.getName().equals(name)) {
found = true;
// delete old file first
final File oldFile = new File(file);
if (oldFile.exists()) {
if (!oldFile.delete()) {
throw new Exception("Could not delete " + file);
}
}
}
final FileOutputStream outFile = new FileOutputStream(file);
int count = 0;
while ((count = inZip.read(data)) != -1) {
outFile.write(data, 0, count);
}
try (FileOutputStream outFile = new FileOutputStream(file)) {
int count = 0;
while ((count = inZip.read(data)) != -1) {
outFile.write(data, 0, count);
}
}
outFile.close();
inZip.closeEntry();
inZip.closeEntry();
}
}
return found;
}
return found;
}
}

View File

@ -147,10 +147,10 @@ public class DownloadInitializer extends Thread {
if (!mMission.running || Thread.interrupted()) return;
}
SharpStream fs = mMission.storage.getStream();
fs.setLength(mMission.offsets[mMission.current] + mMission.length);
fs.seek(mMission.offsets[mMission.current]);
fs.close();
try (SharpStream fs = mMission.storage.getStream()) {
fs.setLength(mMission.offsets[mMission.current] + mMission.length);
fs.seek(mMission.offsets[mMission.current]);
}
if (!mMission.running || Thread.interrupted()) return;

View File

@ -108,7 +108,6 @@ public abstract class Postprocessing implements Serializable {
public void run(DownloadMission target) throws IOException {
this.mission = target;
CircularFileWriter out = null;
int result;
long finalLength = -1;
@ -151,30 +150,32 @@ public abstract class Postprocessing implements Serializable {
return -1;
};
out = new CircularFileWriter(mission.storage.getStream(), tempFile, checker);
out.onProgress = (long position) -> mission.done = position;
try (CircularFileWriter out = new CircularFileWriter(
mission.storage.getStream(), tempFile, checker)) {
out.onProgress = (long position) -> mission.done = position;
out.onWriteError = (err) -> {
mission.psState = 3;
mission.notifyError(ERROR_POSTPROCESSING_HOLD, err);
out.onWriteError = err -> {
mission.psState = 3;
mission.notifyError(ERROR_POSTPROCESSING_HOLD, err);
try {
synchronized (this) {
while (mission.psState == 3)
wait();
try {
synchronized (this) {
while (mission.psState == 3)
wait();
}
} catch (InterruptedException e) {
// nothing to do
Log.e(getClass().getSimpleName(), "got InterruptedException");
}
} catch (InterruptedException e) {
// nothing to do
Log.e(this.getClass().getSimpleName(), "got InterruptedException");
}
return mission.errCode == ERROR_NOTHING;
};
return mission.errCode == ERROR_NOTHING;
};
result = process(out, sources);
result = process(out, sources);
if (result == OK_RESULT)
finalLength = out.finalizeFile();
if (result == OK_RESULT)
finalLength = out.finalizeFile();
}
} else {
result = OK_RESULT;
}
@ -184,9 +185,6 @@ public abstract class Postprocessing implements Serializable {
source.close();
}
}
if (out != null) {
out.close();
}
if (tempFile != null) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();

View File

@ -80,24 +80,15 @@ public class Utility {
@SuppressWarnings("unchecked")
public static <T> T readFromFile(File file) {
T object;
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(file));
try (ObjectInputStream objectInputStream =
new ObjectInputStream(new FileInputStream(file))) {
object = (T) objectInputStream.readObject();
} catch (Exception e) {
Log.e("Utility", "Failed to deserialize the object", e);
object = null;
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (Exception e) {
//nothing to do
}
}
return object;
}

View File

@ -15,6 +15,10 @@
files="ListHelper.java"
lines="281,313"/>
<suppress checks="EmptyBlock"
files="ContentSettingsFragment.java"
lines="244,245"/>
<!-- org.schabi.newpipe.streams -->
<suppress checks="LineLength"
files="WebMWriter.java"