Wednesday, February 6, 2013

Resolve path

This example demonstrate how to use the method Path java.nio.file.Path.resolve(Path other) to resolve the given path against this path.

package javafx_niofile;

import java.io.File;
import java.nio.file.Path;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_NIOFile extends Application {
    
    Label label;
    
    @Override
    public void start(Stage primaryStage) {
        Button btnLoad = new Button();
        btnLoad.setText("Load File");
        btnLoad.setOnAction(btnLoadEventListener);
        
        label = new Label();
        
        VBox rootBox = new VBox();
        rootBox.getChildren().addAll(btnLoad, label);
        
        Scene scene = new Scene(rootBox, 400, 350);
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    EventHandler<ActionEvent> btnLoadEventListener
    = new EventHandler<ActionEvent>(){
  
        @Override
        public void handle(ActionEvent t) {
            FileChooser fileChooser = new FileChooser();
              
            //Set extension filter
            FileChooser.ExtensionFilter extFilter 
                    = new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*");
            fileChooser.getExtensionFilters().add(extFilter);
               
            //Show open file dialog, return a java.io.File object
            File file = fileChooser.showOpenDialog(null);
            
            //obtain a java.nio.file.Path object 
            Path path = file.toPath();
            
            Path parentPath = path.getParent();
            Path partialPath = path.getFileName();
            Path resolvedPath = parentPath.resolve(partialPath);
            
            String fileInfo = "parent = " + parentPath + "\n" +
                    "partial path = " + partialPath + "\n" +
                    "resolve Path = " + resolvedPath;

            label.setText(fileInfo);
        }
    };
}


Resolve path
Resolve path


No comments:

Post a Comment