77import org .schabi .newpipe .extractor .downloader .Response ;
88import org .schabi .newpipe .extractor .exceptions .ReCaptchaException ;
99
10- import java .io .File ;
11- import java .io .FileOutputStream ;
1210import java .io .IOException ;
13- import java .io .OutputStreamWriter ;
1411import java .io .UncheckedIOException ;
15- import java .nio .charset .StandardCharsets ;
1612import java .nio .file .Files ;
1713import java .nio .file .Path ;
1814import java .nio .file .Paths ;
@@ -45,27 +41,30 @@ class RecordingDownloader extends Downloader {
4541 "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\ .){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" ;
4642
4743 private int index = 0 ;
48- private final String path ;
44+ private final Path path ;
4945
5046 /**
5147 * Creates the folder described by {@code stringPath} if it does not exist.
5248 * Deletes existing files starting with {@link RecordingDownloader#FILE_NAME_PREFIX}.
5349 * @param stringPath Path to the folder where the json files will be saved to.
5450 */
5551 public RecordingDownloader (final String stringPath ) {
56- this .path = stringPath ;
57- final Path path = Paths .get (stringPath );
58- final File folder = path .toFile ();
59- if (folder .exists ()) {
60- for (final File file : folder .listFiles ()) {
61- if (file .getName ().startsWith (RecordingDownloader .FILE_NAME_PREFIX )) {
62- file .delete ();
52+ this .path = Paths .get (stringPath );
53+
54+ if (Files .exists (path )) {
55+ try (final var directoryStream = Files .newDirectoryStream (path ,
56+ entry -> entry .getFileName ().toString ()
57+ .startsWith (RecordingDownloader .FILE_NAME_PREFIX ))) {
58+ for (final Path entry : directoryStream ) {
59+ Files .delete (entry );
6360 }
61+ } catch (final IOException ioe ) {
62+ throw new UncheckedIOException (ioe );
6463 }
6564 } else {
6665 try {
6766 Files .createDirectories (path );
68- } catch (IOException e ) {
67+ } catch (final IOException e ) {
6968 throw new UncheckedIOException (e );
7069 }
7170 }
@@ -84,20 +83,13 @@ public Response execute(@Nonnull final Request request) throws IOException,
8483 response .latestUrl ()
8584 );
8685
87- final File outputFile = new File (
88- path + File .separator + FILE_NAME_PREFIX + index + ".json" );
86+ final Path outputPath = path .resolve (FILE_NAME_PREFIX + index + ".json" );
8987 index ++;
90- outputFile .createNewFile ();
91-
92- try (final OutputStreamWriter writer = new OutputStreamWriter (
93- new FileOutputStream (outputFile ), StandardCharsets .UTF_8 )) {
94-
88+ try (final var writer = Files .newBufferedWriter (outputPath )) {
9589 new GsonBuilder ()
96- .setPrettyPrinting ()
97- .create ()
98- .toJson (new TestRequestResponse (request , response ), writer );
99-
100- writer .flush ();
90+ .setPrettyPrinting ()
91+ .create ()
92+ .toJson (new TestRequestResponse (request , response ), writer );
10193 }
10294
10395 return response ;
0 commit comments