Remove characters from a string between two specific characters in java

1

I have a String that contains the file path, and I need to remove the characters that come after the last "/" to the end of the string. Can anyone help me with this? ...

Example:

String comando = "C:/Users/Vinicius/Documents/NetBeansProjects/ProjetoORI/retiramarca.exe"

I want to delete "retiramarca.exe"

 caminho = pesquisaInfo.getText();
    chave = recebeConfirme.getText();

    caminhoInvertido = caminho.replace("\", "/");

if (actionCommand.equals("Encrypt File")) {

    String comando = "C:/Users/Vinicius/Documents/NetBeansProjects/ProjetoORI/inseremarca.exe " + chave + " " + caminhoInvertido;
    try {
        System.out.println(caminhoInvertido.getParentFile());
        Runtime.getRuntime().exec("cmd.exe /C start " + comando);

    } catch (IOException ex) {
    }
    System.out.println(actionCommand);
    JOptionPane.showMessageDialog(null, "Arquivo criptografado");
    
asked by anonymous 15.10.2017 / 17:37

2 answers

4

If you are using the File class, it is It is possible to retrieve this information without regex, using the getParent() method. It returns the folder immediately above the current path of the file.

String caminho = "C:/Users/Vinicius/Documents/NetBeansProjects/ProjetoORI/inseremarca.exe";

System.out.println(new File(caminho).getParent());

Output:

  

C: \ Users \ Vinicius \ Documents \ NetBeansProjects \ ProjectORI

See it works on IDEONE

The getParent() method returns a string with the path one level above the file location.

    
15.10.2017 / 17:50
2

Use the package classes java.nio.* for handle and manipulate file and directory paths

Path path = Paths.get("C:/Users/Vinicius/Documents/NetBeansProjects/ProjetoORI/inseremarca.exe")
                 .getParent();

// C:\Users\Vinicius\Documents\NetBeansProjects\ProjetoORI
System.out.println(path);
    
15.10.2017 / 22:41