调用JFileChooser时,保存的文件不是pdf。用更好的话来说,我叫JFileChooser并用一些名字保存它。然后,当我转到该位置时,文件不具有.pdf扩展名,我尝试使用.getName(),然后向其中添加.pdf扩展名并将其设置为等于.getName(),但这不起作用。我该如何解决?
我为此创建了一个JavaFX项目,并且该窗口上的窗口仅显示一个按钮,单击该按钮时将调用方法“ methodActivate”。
package application;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.apache.pdfbox.pdmodel.*;
public class Main extends Application {
@FXML
private Button button;
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("\\Pdfbox.fxml"));
Scene scene = new Scene(root,500,300);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
@FXML
public void methodActivate() throws IOException{
PDDocument doc =
new PDDocument();
doc.addPage(new PDPage());
boolean bool = false;
try{
JFileChooser fileChooser = new JFileChooser();
File file = fileChooser.getSelectedFile();
doc.save(file);
doc.close();
}
doc.close();
} catch (Exception io){
System.out.println(io);
}
}
}
如果您在JFileChooser窗口中输入的名称(如“ myPdf”)不带.pdf,则它将使用该名称进行保存。JFileChooser不会自动附加文件类型,因此如果您需要此文件,则可以对其进行检查
public File checkFileName(File file) {
if (!file.getAbsolutePath().toLowerCase().endsWith(".pdf")) {
return new File(file.getAbsolutePath() + ".pdf");
} else {
return file;
}
}
有关JFileChooser的更多信息,请参见javadoc。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句