Скачать JavaFX
JavaFX does not provide a built-in mechanism for downloading files from the internet. However, you can achieve file downloading functionality in JavaFX by utilizing Java's standard `URLConnection` class to establish a connection with the desired file URL and then reading the file's content using `InputStream`. Here's an example code snippet demonstrating file downloading in JavaFX:
java
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader extends Application {
private static final String FILE_URL = "https://example.com/samplefile.txt";
private static final String SAVE_PATH = "C:/Downloads/samplefile.txt";
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Button downloadButton = new Button("Download");
downloadButton.setOnAction(event -> {
Task downloadTask = new Task() {
@Override
protected Void call() throws Exception {
downloadFile(FILE_URL, SAVE_PATH);
return null;
}
};
Thread downloadThread = new Thread(downloadTask);
downloadThread.start();
});
VBox root = new VBox(downloadButton);
Scene scene = new Scene(root, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
private void downloadFile(String fileUrl, String savePath) {
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
try (InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer, 0, buffer.length)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code, a JavaFX application is created with a single button labeled "Download". Clicking on this button starts a new thread to download the file specified by `FILE_URL` and save it to the given `SAVE_PATH`. The file downloading logic is implemented in the `downloadFile` method, where it establishes a connection with the file URL, reads the file content using `InputStream`, and saves it to the specified location.
Please note that this is just a basic example, and you might need to handle exceptions, progress reporting, and other aspects depending on your specific requirements.