Merge pull request #4815 from Isira-Seneviratne/Use_try-with-resources

Use try-with-resources.
This commit is contained in:
Stypox 2020-11-21 10:20:49 +01:00 committed by GitHub
commit a86ed1f801
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 84 additions and 137 deletions

View File

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

View File

@ -212,15 +212,14 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
//checkpoint before export //checkpoint before export
NewPipeDatabase.checkpoint(); NewPipeDatabase.checkpoint();
final ZipOutputStream outZip = new ZipOutputStream( try (ZipOutputStream outZip = new ZipOutputStream(new BufferedOutputStream(
new BufferedOutputStream( new FileOutputStream(path)))) {
new FileOutputStream(path))); ZipHelper.addFileToZip(outZip, newpipeDb.getPath(), "newpipe.db");
ZipHelper.addFileToZip(outZip, newpipeDb.getPath(), "newpipe.db");
saveSharedPreferencesToFile(newpipeSettings); saveSharedPreferencesToFile(newpipeSettings);
ZipHelper.addFileToZip(outZip, newpipeSettings.getPath(), "newpipe.settings"); ZipHelper.addFileToZip(outZip, newpipeSettings.getPath(),
"newpipe.settings");
outZip.close(); }
Toast.makeText(getContext(), R.string.export_complete_toast, Toast.LENGTH_SHORT) Toast.makeText(getContext(), R.string.export_complete_toast, Toast.LENGTH_SHORT)
.show(); .show();
@ -230,41 +229,23 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
} }
private void saveSharedPreferencesToFile(final File dst) { private void saveSharedPreferencesToFile(final File dst) {
ObjectOutputStream output = null; try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(dst))) {
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
final SharedPreferences pref final SharedPreferences pref
= PreferenceManager.getDefaultSharedPreferences(requireContext()); = PreferenceManager.getDefaultSharedPreferences(requireContext());
output.writeObject(pref.getAll()); output.writeObject(pref.getAll());
output.flush();
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (final IOException ex) {
ex.printStackTrace();
}
} }
} }
private void importDatabase(final String filePath) { private void importDatabase(final String filePath) {
// check if file is supported // check if file is supported
ZipFile zipFile = null; try (ZipFile zipFile = new ZipFile(filePath)) {
try {
zipFile = new ZipFile(filePath);
} catch (final IOException ioe) { } catch (final IOException ioe) {
Toast.makeText(getContext(), R.string.no_valid_zip_file, Toast.LENGTH_SHORT) Toast.makeText(getContext(), R.string.no_valid_zip_file, Toast.LENGTH_SHORT)
.show(); .show();
return; return;
} finally {
try {
zipFile.close();
} catch (final Exception ignored) {
}
} }
try { try {
@ -312,9 +293,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
} }
private void loadSharedPreferences(final File src) { private void loadSharedPreferences(final File src) {
ObjectInputStream input = null; try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(src))) {
try {
input = new ObjectInputStream(new FileInputStream(src));
final SharedPreferences.Editor prefEdit = PreferenceManager final SharedPreferences.Editor prefEdit = PreferenceManager
.getDefaultSharedPreferences(requireContext()).edit(); .getDefaultSharedPreferences(requireContext()).edit();
prefEdit.clear(); prefEdit.clear();
@ -338,14 +317,6 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
prefEdit.commit(); prefEdit.commit();
} catch (final IOException | ClassNotFoundException e) { } catch (final IOException | ClassNotFoundException e) {
e.printStackTrace(); 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.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.util.LinkedList; import java.util.LinkedList;
@ -106,7 +105,6 @@ public final class StateSaver {
+ "writeRead = [" + writeRead + "]"); + "writeRead = [" + writeRead + "]");
} }
FileInputStream fileInputStream = null;
try { try {
Queue<Object> savedObjects Queue<Object> savedObjects
= STATE_OBJECTS_HOLDER.remove(savedState.getPrefixFileSaved()); = STATE_OBJECTS_HOLDER.remove(savedState.getPrefixFileSaved());
@ -127,10 +125,12 @@ public final class StateSaver {
return null; return null;
} }
fileInputStream = new FileInputStream(file); try (FileInputStream fileInputStream = new FileInputStream(file);
final ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); ObjectInputStream inputStream = new ObjectInputStream(fileInputStream)) {
//noinspection unchecked //noinspection unchecked
savedObjects = (Queue<Object>) inputStream.readObject(); savedObjects = (Queue<Object>) inputStream.readObject();
}
if (savedObjects != null) { if (savedObjects != null) {
writeRead.readFrom(savedObjects); writeRead.readFrom(savedObjects);
} }
@ -138,13 +138,6 @@ public final class StateSaver {
return savedState; return savedState;
} catch (final Exception e) { } catch (final Exception e) {
Log.e(TAG, "Failed to restore state", e); Log.e(TAG, "Failed to restore state", e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (final IOException ignored) {
}
}
} }
return null; return null;
} }
@ -227,7 +220,6 @@ public final class StateSaver {
} }
} }
FileOutputStream fileOutputStream = null;
try { try {
File cacheDir = new File(cacheDirPath); File cacheDir = new File(cacheDirPath);
if (!cacheDir.exists()) { if (!cacheDir.exists()) {
@ -258,19 +250,14 @@ public final class StateSaver {
} }
} }
fileOutputStream = new FileOutputStream(file); try (FileOutputStream fileOutputStream = new FileOutputStream(file);
final ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream)) {
outputStream.writeObject(savedObjects); outputStream.writeObject(savedObjects);
}
return new SavedState(prefixFileName, file.getAbsolutePath()); return new SavedState(prefixFileName, file.getAbsolutePath());
} catch (final Exception e) { } catch (final Exception e) {
Log.e(TAG, "Failed to save state", e); Log.e(TAG, "Failed to save state", e);
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (final IOException ignored) { }
}
} }
return null; return null;
} }

View File

@ -45,15 +45,15 @@ public final class ZipHelper {
public static void addFileToZip(final ZipOutputStream outZip, final String file, public static void addFileToZip(final ZipOutputStream outZip, final String file,
final String name) throws Exception { final String name) throws Exception {
final byte[] data = new byte[BUFFER_SIZE]; final byte[] data = new byte[BUFFER_SIZE];
final FileInputStream fi = new FileInputStream(file); try (FileInputStream fi = new FileInputStream(file);
final BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE); BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE)) {
final ZipEntry entry = new ZipEntry(name); final ZipEntry entry = new ZipEntry(name);
outZip.putNextEntry(entry); outZip.putNextEntry(entry);
int count; int count;
while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) { while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
outZip.write(data, 0, count); 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, public static boolean extractFileFromZip(final String filePath, final String file,
final String name) throws Exception { 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( boolean found = false;
new BufferedInputStream(
new FileInputStream(filePath)));
final byte[] data = new byte[BUFFER_SIZE]; ZipEntry ze;
while ((ze = inZip.getNextEntry()) != null) {
boolean found = false; if (ze.getName().equals(name)) {
found = true;
ZipEntry ze; // delete old file first
while ((ze = inZip.getNextEntry()) != null) { final File oldFile = new File(file);
if (ze.getName().equals(name)) { if (oldFile.exists()) {
found = true; if (!oldFile.delete()) {
// delete old file first throw new Exception("Could not delete " + file);
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); try (FileOutputStream outFile = new FileOutputStream(file)) {
int count = 0; int count = 0;
while ((count = inZip.read(data)) != -1) { while ((count = inZip.read(data)) != -1) {
outFile.write(data, 0, count); 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; if (!mMission.running || Thread.interrupted()) return;
} }
SharpStream fs = mMission.storage.getStream(); try (SharpStream fs = mMission.storage.getStream()) {
fs.setLength(mMission.offsets[mMission.current] + mMission.length); fs.setLength(mMission.offsets[mMission.current] + mMission.length);
fs.seek(mMission.offsets[mMission.current]); fs.seek(mMission.offsets[mMission.current]);
fs.close(); }
if (!mMission.running || Thread.interrupted()) return; 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 { public void run(DownloadMission target) throws IOException {
this.mission = target; this.mission = target;
CircularFileWriter out = null;
int result; int result;
long finalLength = -1; long finalLength = -1;
@ -151,30 +150,32 @@ public abstract class Postprocessing implements Serializable {
return -1; return -1;
}; };
out = new CircularFileWriter(mission.storage.getStream(), tempFile, checker); try (CircularFileWriter out = new CircularFileWriter(
out.onProgress = (long position) -> mission.done = position; mission.storage.getStream(), tempFile, checker)) {
out.onProgress = (long position) -> mission.done = position;
out.onWriteError = (err) -> { out.onWriteError = err -> {
mission.psState = 3; mission.psState = 3;
mission.notifyError(ERROR_POSTPROCESSING_HOLD, err); mission.notifyError(ERROR_POSTPROCESSING_HOLD, err);
try { try {
synchronized (this) { synchronized (this) {
while (mission.psState == 3) while (mission.psState == 3)
wait(); 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) if (result == OK_RESULT)
finalLength = out.finalizeFile(); finalLength = out.finalizeFile();
}
} else { } else {
result = OK_RESULT; result = OK_RESULT;
} }
@ -184,9 +185,6 @@ public abstract class Postprocessing implements Serializable {
source.close(); source.close();
} }
} }
if (out != null) {
out.close();
}
if (tempFile != null) { if (tempFile != null) {
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
tempFile.delete(); tempFile.delete();

View File

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

View File

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