# Wie binde ich eine JavaFX ProgressBar an eine Datei Übertragung?



## michadaniel (16. Mrz 2016)

Hallo,
Ich habe einen FileClient und einen FileServer gemacht, weiß aber nicht, wie ich den Fortschritt der Datei Übertragung an die ProgressBar binden kann.
FileClient:

```
public class FileClient extends Application implements FileTransfer {
    public static final int PORT = 7070;
    public static final String ADDRESS = "michadaniel4.ddns.net";
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox();
        Button button = new Button("Choose your File...");
        button.setPrefWidth(400);
        button.setPrefHeight(50);
        ProgressBar progressBar = new ProgressBar();
        progressBar.setPrefWidth(400);
        progressBar.setPrefHeight(50);
        root.getChildren().addAll(button, progressBar);
        Scene scene = new Scene(root, 400, 100);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.sizeToScene();
        primaryStage.setTitle("File Client");
        primaryStage.show();
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                File file = new FileChooser().showOpenDialog(null).getAbsoluteFile();
                Task task = new Task() {
                    @Override
                    protected Object call() throws Exception {
                        try {
                            Socket socket = new Socket(ADDRESS, PORT);
                            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                            byte[] bytes = readData(file.getAbsolutePath());
                            dataOutputStream.writeInt(bytes.length);
                            dataOutputStream.write(bytes);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                };
                new Thread(task).start();
            }
        });
    }
    @Override
    public boolean writeData(byte[] data, String fileName) {
        File file = new File(fileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data);
            fileOutputStream.flush();
            return true;
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems writing data to " + file);
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
            } catch (IOException e) {
                System.err.println("FileOutputStream cannot be closed");
            }
        }
        return false;
    }
    @Override
    public byte[] readData(String fileName) {
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        byte[] data = null;
        try {
            fileInputStream = new FileInputStream(file);
            data = new byte[(int) file.length()];
            fileInputStream.read(data);
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems reading data from " + file);
        } finally {
            try {
                if (fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                System.err.println("FileInputStream cannot be closed");
            }
        }
        return data;
    }
}
```

FileServer:

```
public class FileServer implements FileTransfer {
    public static final int PORT = 7070;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true) {
                Socket socket = serverSocket.accept();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                long start = System.currentTimeMillis();
                int length = dataInputStream.readInt();
                if (length > 0) {
                    byte[] bytes = new byte[length];
                    dataInputStream.readFully(bytes);
                    new FileServer().writeData(bytes, "C:\\Users\\Michadaniel\\IdeaProjects\\FileTransfer\\in\\test.jar");
                }
                long stop = System.currentTimeMillis();
                double time = (stop - start) / 1000D;
                System.out.println("Time: " + time + "s");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean writeData(byte[] data, String fileName) {
        File file = new File(fileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data);
            fileOutputStream.flush();
            return true;
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems writing data to " + file);
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
            } catch (IOException e) {
                System.err.println("FileOutputStream cannot be closed");
            }
        }
        return false;
    }

    @Override
    public byte[] readData(String fileName) {
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        byte[] data = null;
        try {
            fileInputStream = new FileInputStream(file);
            data = new byte[(int) file.length()];
            fileInputStream.read(data);
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems reading data from " + file);
        } finally {
            try {
                if (fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                System.err.println("FileInputStream cannot be closed");
            }
        }
        return data;
    }
}
```


----------



## dzim (17. Mrz 2016)

Erst mal etwas zum Lesen:
1) http://www.java2s.com/Code/Java/JavaFX/ProgressBarandBackgroundProcesses.htm
2) http://stackoverflow.com/questions/32843078/javafx-progress-bar-show-file-upload-status --> http://stackoverflow.com/a/32844342
3) http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/

Idealerweise also solltest du einen Service oder wenigstens einen Task implementieren, die den Progress updaten. Auf diese Progress-Update kannst du hören - du kannst also den ProgressBar an den Progress binden. Wichtig aber ist generell, dass du auch weisst, wie viel Daten du erhalten willst (sonst wird es schwer, einen Progress darzustellen).
Ich habe keine Fix und Fertige Lösung parat, würde aber in etwa so vorgehen:
Der Server bietet Methode für den Download und die Abfrage der Grösse an (oder du sendest als allererstes - vor den eigentlichen File-Daten, die Grösse des Files in dem Stream und legst dir ein Trennzeichen fest, ab wann die Nutzdaten, also das File kommt).
Der Client fragt jetzt die Grösse ab und passt seinen Progress entsprechend an (oder parst sie entsprechend aus dem Header der Daten, die der Server sendet). Dann wird nach jedem Block der Progress des Tasks geupdated und entsprechend updated sich auch die ProgressBar.

Wird dir in etwa klar, was ich meine?


----------



## michadaniel (17. Mrz 2016)

Ich habe jetzt zwar deine Antwort nicht so richtig beachtet, das tut mir auch leid, aber ich habe dafür nach ewigkeiten eine Lösung gefunden, welche auch gut funktioniert:

FileClient:

```
package net.ddns.michadaniel4.filetransfer;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.net.Socket;

/**
* Created by Michadaniel on 14.03.2016.
*/
public class FileClient extends Application implements FileTransfer {
    public static final int PORT = 7070;
    public static final String ADDRESS = "michadaniel4.ddns.net";

    public ProgressBar progressBar = new ProgressBar();

    public Task task = null;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox();
        Button button = new Button("Choose your File...");
        button.setPrefWidth(400);
        button.setPrefHeight(50);
        progressBar.setPrefWidth(400);
        progressBar.setPrefHeight(50);
        root.getChildren().addAll(button, progressBar);
        Scene scene = new Scene(root, 400, 100);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.sizeToScene();
        primaryStage.setTitle("File Client");
        primaryStage.show();

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                File file = new FileChooser().showOpenDialog(null).getAbsoluteFile();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Socket socket = new Socket(ADDRESS, PORT);
                            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()) {
                                @Override
                                public void write(byte b[], int off, int len) throws IOException {
                                    if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
                                        throw new IndexOutOfBoundsException();

                                    task = new Task() {
                                        @Override
                                        protected Object call() throws Exception {
                                            for (int i = 0; i < len; i++) {
                                                write(b[off + i]);
                                                updateProgress(i, len);
                                            }
                                            return null;
                                        }
                                    };
                                    Platform.runLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressBar.progressProperty().bind(task.progressProperty());
                                        }
                                    });
                                    task.run();
                                }
                            };
                            byte[] bytes = readData(file.getAbsolutePath());
                            dataOutputStream.writeUTF(file.getName());
                            dataOutputStream.writeInt(bytes.length);
                            dataOutputStream.write(bytes);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    @Override
    public boolean writeData(byte[] data, String fileName) {
        File file = new File(fileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data);
            fileOutputStream.flush();
            return true;
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems writing data to " + file);
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
            } catch (IOException e) {
                System.err.println("FileOutputStream cannot be closed");
            }
        }
        return false;
    }

    @Override
    public byte[] readData(String fileName) {
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        byte[] data = null;
        try {
            fileInputStream = new FileInputStream(file);
            data = new byte[(int) file.length()];
            fileInputStream.read(data);
        } catch (FileNotFoundException e) {
            System.err.println(file + " doesn't exist!");
        } catch (IOException e) {
            System.err.println("Problems reading data from " + file);
        } finally {
            try {
                if (fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                System.err.println("FileInputStream cannot be closed");
            }
        }
        return data;
    }
}
```


----------

