Saving result in txt file

1

How would I save the output of the program to txt file? in the example I call cmd and ask you to do something, I wanted to save the result to a text file.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class test {

public static void main(String[] args) throws IOException {



    String line;
    Process saida;

    //executa o processo e armazena a referência em 'Saida'

    saida = Runtime.getRuntime().exec("cmd /c ipconfig");



    //pega o retorno do processo

    BufferedReader stdInput = new BufferedReader(new 
            InputStreamReader(saida.getInputStream()));

    //printa o retorno
    while ((line = stdInput.readLine()) != null) {
        System.out.println(line);

    }
    stdInput.close();

}
}
    
asked by anonymous 30.04.2017 / 23:38

1 answer

0

Here's a very simple way, based on the docs .

  

Include these imports:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
  

Create this path :

Path path = Paths.get("/endereco/do/seu/arquivo.txt");
  

And change your System.out.println(line); to:

Files.write(path, line.getBytes(), StandardOpenOption.APPEND);
  

To create a file, instead of using an existing one, add it shortly after the creation of path :

try {
    Files.createFile(path);
} catch (Exception e) {
    System.err.println(e);
}
    
01.05.2017 / 02:07