2016-04-26 15 views
0

私はJavaFxで新しく、Filechooserで既に選択されているファイルを自分のプロジェクトフォルダにコピーする方法を知りました。選択したファイルをプロジェクトディレクトリにコピー

public void ButtonAction(ActionEvent event) { 
    FileChooser fc = new FileChooser(); 
    fc.setTitle("attach a file"); 
    File selectedFile = fc.showOpenDialog(null); 

    if (selectedFile != null) { 
     file1.setText("selectionned file : " + selectedFile.getAbsolutePath()); 

     //the code to copy the selected file goes here// 

    } else{ 
     file1.setText("no file attached"); 
    } 

答えて

1

あなたは例えば、ファイルをコピーするFilesクラスを使用することができます。:とにかく感謝を解決

Files.copy(selectedFile.toPath, targetDirPath); 
1

問題。

Path from = Paths.get(selectedFile.toURI()); 
     Path to = Paths.get("pathdest\\file.exe"); 
     CopyOption[] options = new CopyOption[]{ 
       StandardCopyOption.REPLACE_EXISTING, 
       StandardCopyOption.COPY_ATTRIBUTES 
     }; 
     Files.copy(from, to, options); 
0

このメソッドの実際のコードをコピーして見ていると(それのいくつかは、単に動作しないので)上記のコードとのトラブルのビットを持つ人のためのそれは少し簡単にするために:

private Path to; 
private Path from; 
private File selectedFile; 

private void handleFileLocationSearcher() throws IOException { 
    FileChooser fc = new FileChooser(); 
    fc.setTitle("Attach a file"); 
    selectedFile = fc.showOpenDialog(null); 

    if (selectedFile != null) { 
     from = Paths.get(selectedFile.toURI()); 
     to = Paths.get("Your destination path" + selectedFile.getName()); 
     Files.copy(from.toFile(), to.toFile()); 
    } 
} 

selectedFile.toString()またはselectedFile.getName()を使用してテキストフィールドに追加するか、一般的にファイルセレクタで取得しようとしているファイルのパスまたは名前を取得できます。

変数がクラス内のどこでも使用できるので、別のボタンを押したときにそのアプリケーションを実行する場合は、アプリケーション内の別の場所にFiles.copy(from.toFile(), to.toFile());を使用することもできます。これを行う必要がない場合は、メソッド内にローカル変数を作成するだけです。

関連する問題