我希望在运行时将我的文件从.jar保护到本地FS。如果我用netbeans开始这个,我可以保护文件但是如果我启动我的dist .jar我发现没有文件......
我尝试使用MyClass.clas.getResource(“src / scripteInklErklaerung / Mustertest_24STUNDENBELASTUNG.tts”)。toExternalForm ...
有人能说出正确的方法吗?
我有一个带有5个CheckBoxes的.fxml文件,如果你选择其中的多个,你可以点击safe-Button将文件保存到本地FS:
@FXML Button btn_infoAusf;
@FXML CheckBox cb_ausfuehrlich;
@FXML CheckBox cb_eingang;
@FXML CheckBox cb_ausgang;
@FXML CheckBox cb_schnell;
@FXML CheckBox cb_24;
@FXML Button btn_saveToStick;
File pathAusf = new File("/scripteInklErklaerung/Mustertest_AUSFUEHRLICH.tts");
File pathEing = new File("src/scripteInklErklaerung/Mustertest_EINGANG.tts");
File pathAusg = new File("src/scripteInklErklaerung/Mustertest_AUSGANG.tts");
File pathSchnell = new File("src/scripteInklErklaerung/Mustertest_SCHNELL.tts");
File path24 = new File("src/scripteInklErklaerung/Mustertest_24STUNDENBELASTUNG.tts");
ObservableList<CheckBox> cb = FXCollections.observableArrayList();
ObservableList<File> scripte = FXCollections.observableArrayList();
Stage primaryStage = new Stage();
public void getPrimaryStage(Stage stage){
this.primaryStage=stage;
}
public void createPath(){
if(cb_ausfuehrlich.isSelected()){
scripte.add(pathAusf);
}
if(cb_eingang.isSelected()){
scripte.add(pathEing);
}
if(cb_ausgang.isSelected()){
scripte.add(pathAusg);
}
if(cb_schnell.isSelected()){
scripte.add(pathSchnell);
}
if(cb_24.isSelected()){
scripte.add(path24);
}
}
public void saveTestsToStick(ActionEvent event){
try{
createPath();
System.getProperty("java.class.path");
DirectoryChooser fileSaveDialog = new DirectoryChooser();
fileSaveDialog.setTitle("Vorgefertigte Dauertest speichern Pfad: toolhouseUSB-Stick/testlx/DAUERTEST");
Stage stage = (Stage) btn_saveToStick.getScene().getWindow();
stage.close();
File saveFile = fileSaveDialog.showDialog(primaryStage);
for(int i=0;i<scripte.size();i++){
File realPath = new File(saveFile+"\\"+scripte.get(i).getName());
Files.copy(scripte.get(i).toPath(), realPath.toPath(), REPLACE_EXISTING);
System.out.println(scripte.get(i));
}
}catch(NullPointerException|IOException ex){System.out.println(ex);}
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
btn_saveToStick.setOnAction(this::saveTestsToStick);
cb.add(cb_ausfuehrlich);
}
}
答案 0 :(得分:0)
如果您在jar中引用文件,我认为您需要一个绝对路径,所以我会尝试使用:
MyClass.clas.getResource("/src/scripteInklErklaerung/Mustertest_24STUNDENBELASTUNG.tts")
注意路径开头的/
。
如果这没有用,可能是Files
无法使用Jars内部的路径。在这种情况下,从资源中获取InputStream
,为目标文件打开FileOutputStream
,然后从InputStream中读取内容并将其写入OutputStream,以手动将文件复制到Jar中:
public static void copyStream(final InputStream fromStream, final OutputStream toStream) throws IOException {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fromStream.read(buffer)) != -1) {
toStream.write(buffer, 0, bytesRead);
}
}