如何使用 JavaFX WebView 打开本地文本文件

How to open local text file with JavaFX WebView

是否可以使用 JavaFX WebView 打开本地文本文件?我尝试了以下代码,但没有用。我该如何启用它?

WebView wv = new WebView();
wv.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {

    @Override
    public WebEngine call(PopupFeatures p) {
        Stage stage = new Stage(StageStyle.UTILITY);
        WebView wv2 = new WebView();
        stage.setScene(new Scene(wv2));
        stage.show();
        return wv2.getEngine();
    }
});

wv.getEngine().loadContent("<a href="file:///C:\Users\Dev\infor.txt">Open File</a>");

StackPane root = new StackPane();
root.getChildren().add(wv);

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();

是的,您可以使用 JavaFX WebView 打开本地文本文件。

示例应用程序:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class WebViewWithLocalText extends Application {

    @Override
    public void start(Stage stage) throws MalformedURLException {
        String location =
                new File(
                        System.getProperty("user.dir") + File.separator + "test.txt"
                ).toURI().toURL().toExternalForm();

        System.out.println(location);

        WebView webView = new WebView();
        webView.getEngine().load(location);

        // use loadContent instead of load if you want a link to a file.
        // webView.getEngine().loadContent(
        //     "<a href=\"" + location + "\">Open File</a>"
        // );

        Scene scene = new Scene(webView);
        stage.setScene(scene);
        stage.show();
    }

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

在 运行 程序时 System.out 报告的位置放置一个文本文件。

示例输出:

您提供的代码中存在一些错误:

  1. 您不会转义引号。
  2. 您没有提供有效的文件 URI,您提供了 windows 以文件协议为前缀的路径。
  3. 您对路径和驱动器说明符进行了硬编码,这可能不是系统之间的可移植解决方案。

我没有要测试的 windows 机器,但也许像这样的东西适用于您的绝对路径。

wv.getEngine().loadContent("<a href=\"file:///C:/Users/Dev/infor.txt\">Open File</a>");

另请参阅: