public void copyFile(File sourceFile, File destinationFile, Consumer<ProgressEntity> onChange) throws IOException, InterruptedException { int fileSize = (int) sourceFile.length(); float totalDataRead = 0.0F; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile), BLOCK_SIZE)) { byte[] data = new byte[BLOCK_SIZE]; int i; while ((i = inputStream.read(data, 0, BLOCK_SIZE)) >= 0) { totalDataRead += i; outputStream.write(data, 0, i); int percentCopied = (int) (totalDataRead * 100 / fileSize); onChange.accept(new ProgressEntity.Builder().withPercent(percentCopied).build()); if (Thread.interrupted()) { throw new InterruptedException("The copy process was interrupted"); } } inputStream.close(); outputStream.close(); } }
.accept(new ProgressEntity.Builder() .withPercent( (double) countingInputStream.getCount() / (double) finalSize * (double) 100)
.accept(new ProgressEntity.Builder() .withPercent( (double) countingInputStream.getCount() / (double) finalSize * (double) 100)
/** * updates the progress indicator * * @param state current state (e.g. if download finished) * @param percentage progress percentage * @param progressText e.g. downloaded x of y bytes * @param onChange consumer to show the download progress (e.g. a progress bar) */ private void changeState(ProgressState state, float percentage, String progressText, Consumer<ProgressEntity> onChange) { if (onChange != null) { ProgressEntity currentState = new ProgressEntity.Builder().withPercent(percentage).withState(state) .withProgressText(progressText).build(); onChange.accept(currentState); } }
private void changeState(double percentage, Consumer<ProgressEntity> onChange) { if (onChange != null) { onChange.accept( new ProgressEntity.Builder().withPercent(percentage).withProgressText(WAIT_MESSAGE).build()); } } }