Difficulty to define the path where given txt will be created

1

The following method generates a txt containing certain information:

public static void gravarIp(String ip)
{   
    try {
        File arquivo = new File("ip.txt");  
        FileOutputStream fos = new FileOutputStream(arquivo);  
        String texto = ip;  
        fos.write(texto.getBytes());  
        fos.close();
        atualizarPortal(ip);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

However, this txt is being generated in the place where the statement is executed:

c:\>java -cp c:\users\fabio\desktop EnviarIp

That is, if the above statement is executed and I am in the root of c: txt will be generated there. How do I generate the txt in the same root as the SendIp file without specifying the absolute path in the source code?

    
asked by anonymous 12.11.2015 / 12:05

2 answers

2

The maximum that I was able to generate was a file in a fixed location as the User folder (it can be a subfolder inside it if you wish) or an absolute Path as C: disk, Program Files folder etc.

It looks like this:

import java.io.*;

public class Teste {
    public static void main(String[] args) {        
        try {       
            File arquivo = new File(System.getProperty("user.home"), "ip.txt");  
            FileOutputStream fos = new FileOutputStream(arquivo);  
            String texto = "192.168.1.1";  
            fos.write(texto.getBytes());  
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Unfortunately I could not generate the file in the same place as the / jar class.

Answer found with the help of the user's own question:

import java.io.*;

public class Teste {
    public static void main(String[] args) {        
        try {
            String diretorio = System.getProperty("user.dir");      
            File arquivo = new File(diretorio, "ip.txt");  
            FileOutputStream fos = new FileOutputStream(arquivo);  
            String texto = "192.168.1.1";  
            fos.write(texto.getBytes());  
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Searching the System.getProperty("user.dir") property is the directory where the class is. Sorry for not finding it before and thank you.

Source: System Properties - Java

    
12.11.2015 / 13:00
1

If you want the current path and not a fixed path:

String path = new File(".").getCanonicalPath();
    
12.11.2015 / 13:50