我的问题是当我尝试在我的 JavaFX 应用程序中显示 pdf 时,当我从 ide 运行时页面加载速度很快
但是它变慢并且显示没有响应,我将堆设置为 3000mp 没有任何区别
我在我的项目中使用**PDFViewerFX **库并编辑缓冲代码以提高性能,
现在在 ide 中速度更快,但 jar 文件没有任何改进,
在 ide 或 jar 中运行有什么不同?
hear是显示pdf的代码
public void loadPDF(URL url) throws IOException {
loadPDF(new BufferedInputStream(url.openConnection().getInputStream()));
}
private static final Logger logger = LoggerFactory.getLogger(PDFDisplayer.class);
private static final int THREAD_POOL_SIZE = 5;
private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
private final ThreadGroup group = new ThreadGroup("my-thread-pool");
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, "my-thread-" + new AtomicInteger(1), 0);
t.setDaemon(false);
return t;
}
});
private final ObjectProperty<Consumer<Task<String>>> onLoaderTaskPresent =
new SimpleObjectProperty<>();
private boolean pdfJsLoaded;
public void loadPDF(InputStream inputStream) {
if (inputStream == null)
return;
Task<String> task = buildLoadingTask(inputStream);
final Consumer<Task<String>> onLoaderTaskPresent = this.onLoaderTaskPresent.get();
if (onLoaderTaskPresent != null) {
Platform.runLater(() -> onLoaderTaskPresent.accept(task));
}
THREAD_POOL.submit(task);
}
/**
* @deprecated Use {@link #loadPDF(InputStream)} instead
*/
@Deprecated
public void displayPdf(InputStream inputStream) throws IOException {
loadPDF(inputStream);
}
private void loadInputStream(InputStream inputStream) {
Task<String> loadingTask = buildLoadingTask(inputStream);
THREAD_POOL.submit(loadingTask);
loadingTask.setOnSucceeded(event -> {
String js = loadingTask.getValue();
if (js != null) {
try {
webView.getEngine().executeScript(js);
} catch (Exception ex) {
if (!pdfJsLoaded) {
loadScript = js;
}
}
}
THREAD_POOL.shutdown();
});
loadingTask.setOnFailed(event -> {
Throwable ex = event.getSource().getException();
if (ex != null) {
// Handle error more gracefully
showErrorDialog("Failed to execute script", (Exception) ex);
}
});
}
private Task<String> buildLoadingTask(InputStream inputStream) {
final Task<String> task = new Task<String>() {
@Override
protected String call() throws Exception {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
long contentSize = inputStream.available();
long onePercent = contentSize / 100;
int allReadBytesCount = 0;
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) >= 0) {
allReadBytesCount += bytesRead;
outputStream.write(buf, 0, bytesRead);
if (onePercent > 0) {
double percent = allReadBytesCount / (double) onePercent;
updateProgress(percent, 100d);
}
if (this.isCancelled()) {
return null;
}
}
byte[] data = outputStream.toByteArray();
String base64 = Base64.getEncoder().encodeToString(data);
//JS Function declaration
return "openFileFromBase64('" + base64 + "');";
} finally {
inputStream.close();
}
}
};
task.valueProperty().addListener((observable, oldValue, js) -> {
if (js != null) {
try {
webView.getEngine().executeScript(js);
} catch (Exception ex) {
if (!pdfJsLoaded) loadScript = js;
}
}
});
return task;
}
@SuppressWarnings("all")
public void setSecondaryToolbarToggleVisibility(boolean value) {
setVisibilityOf("secondaryToolbarToggle", value);
String js;
if (value){
js = new StringBuilder()
.append("var element = document.getElementsByClassName('verticalToolbarSeparator')[0];")
.append("element.style.display = 'inherit';")
.append("element.style.visibility = 'inherit';")
.toString();
} else {
js = new StringBuilder()
.append("var element = document.getElementsByClassName('verticalToolbarSeparator')[0];")
.append("element.style.display = 'none';")
.append("element.style.visibility = 'hidden';")
.toString();
}
try {
webView.getEngine().executeScript(js);
} catch (Exception ex){
if (!pdfJsLoaded) toExecuteWhenPDFJSLoaded += js;
}
}
@SuppressWarnings("all")
public void setVisibilityOf(String id, boolean value){
String css;
if (value) {
css = new StringBuilder()
.append("document.getElementById('" + id + "').style.display = 'inherit';")
.append("document.getElementById('" + id + "').style.visibility = 'inherit';")
.toString();
} else {
css = new StringBuilder()
.append("document.getElementById('" + id + "').style.display = 'none';")
.append("document.getElementById('" + id + "').style.visibility = 'hidden';")
.toString();
}
try {
webView.getEngine().executeScript(css);
} catch (Exception ex) {
if (!pdfJsLoaded) this.toExecuteWhenPDFJSLoaded += css;
}
}
public int getActualPageNumber(){
try {
return (int) webView.getEngine().executeScript("PDFViewerApplication.page;");
} catch (Exception e) {
return 0;
}
}
private void showErrorDialog(String message, Exception ex) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(message);
alert.setContentText(ex.getMessage());
alert.showAndWait();
}
public int getTotalPageCount(){
try {
return (int) webView.getEngine().executeScript("PDFViewerApplication.pagesCount;");
} catch (Exception e) {
return 0;
}
}
public void navigateByPage(int pageNum) {
String jsCommand = "goToPage(" + pageNum + ");";
try {
webView.getEngine().executeScript(jsCommand);
} catch (Exception ex) {
if (!pdfJsLoaded) toExecuteWhenPDFJSLoaded += jsCommand;
}
}
public void executeScript(String js) {
try {
this.webView.getEngine().executeScript(js);
} catch (Exception ex) {
if (!pdfJsLoaded) toExecuteWhenPDFJSLoaded += String.format("%s;", js);
}
}
private WebView createWebView() {
WebView webView = new WebView();
webView.setContextMenuEnabled(false);
WebEngine engine = webView.getEngine();
String url;
try {
URL resourceUrl = getClass().getResource("/pdfjs_2.2.228/web/viewer.html");
engine.setJavaScriptEnabled(true);
engine.load(resourceUrl.toString());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
engine.getLoadWorker()
.stateProperty()
.addListener(
new ChangeListener<Worker.State>() {
@Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("java", new JSLogListener());
if (newValue == Worker.State.SUCCEEDED) {
try {
pdfJsLoaded = true;
if (loadScript != null) {
logger.debug("PDF already loaded");
engine.executeScript(loadScript);
}
engine.executeScript(toExecuteWhenPDFJSLoaded);
toExecuteWhenPDFJSLoaded = null;
observable.removeListener(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
});
return webView;
}
public Parent toNode() {
if (webView == null)
return webView = createWebView();
else
return webView;
}
我使用了 Marven 和 artifact with jest dependency 我用过并且性能是一样的
我用openjdk18和oracle jdk18结果一样
当我提取 jar 并像这样从 cmd 运行 main.class 时,它工作顺利
java -cp ./pdfcheck-1.0 pdfcheck.main
我说这很可能是 ide 运行我的代码的方式。 对发生的事情和原因有何解释?