Search code examples
javafiledump

open and read random .txt with java aplication executable not knowing the rute of .txt


I would like to know how I can open and display a .txt in a Java application . The .txt is associated with the application and when you click on it , the application opens, but the file does not get to be shown if not by passing a fixed route.

I've got to show it but only if the .txt file is in the same directory as the jar file and run the application only if directly . The direct access from the .txt opens the application but nothing more .

I have this code , you see the path step them directly . I want you to take from the .txt has been clicked .

    FileReader f = new FileReader("archivo.txt");
    BufferedReader b = new BufferedReader(f);

    String linea_cliente = b.readLine();
    StringTokenizer datos_cliente = new StringTokenizer(linea_cliente,";");
    while(datos_cliente.hasMoreTokens()){
        pedido.setText(datos_cliente.nextToken());
        id_cliente.setText(datos_cliente.nextToken());
        nom_cli.setText(datos_cliente.nextToken());
        dir_cli.setText(datos_cliente.nextToken());
        cp_cli.setText(datos_cliente.nextToken());
        loc_cli.setText(datos_cliente.nextToken());
        prov_cli.setText(datos_cliente.nextToken());
        pais_cli.setText(datos_cliente.nextToken());
        obs_cli.setText(datos_cliente.nextToken());
    } 

Sorry for my bad English . Thank You ;)


Solution

  • FileReader f = new FileReader("archivo.txt");
    

    Implies that archivo.txt is a relative path. Relative meaning in relation to the current executable. It is an implied .\archivo.txt

    You can place it in a sub directory and use a relative path again like .\myfiles\textfiles\archivo.txt where .\ is the location of your jar.

    If you want to input many different text files and you don't know where they will be then you can use arguments. From the command line it would look like:

    > java jar myproj.jar C:\test\foo\archivo.txt
    

    And to access it in main() use:

    String filePath = args[0]
    FileReader f = new FileReader(filePath);
    

    If you want it to be portable accross many systems you'll need to take advantage of environment variables to get your base path and then attach the route to your .txt file to the base.

    Sorry, it was a little unclear what you were asking for so I covered a few common cases, let me know if you need clarification.