Read files. bat java

Asked

Viewed 340 times

1

Someone could ask me a question, as I do to read and edit a file . bat by java, in case I have a file . bat I want to open it in . txt to change, the method below is what I am using

public void editarArquivo() throws SQLException, IOException{
    DirControle dir = new DirControle();
    String directory = dir.selectedDir_CB().toString().replace("[", "").replace("]", "");
    Runtime.getRuntime().exec("notepad "+directory+"\\"+getPasta()+"\\"+getArchive());
}                                                                                      

where directory is the path to my file getPasta() is a folder before the file and getArchive() the file itself

1 answer

0


Java is indifferent to file extensions and yes, only to its content, and a Bat file is a text, so for you to write a file in Java, could do so:

//Essa pasta é relativa ao lugar de execucao do programa.
File file = new File("diretorio/minha-saida.bat");//Como eu disse, é so texto
BufferedWriter writer = new BufferedWriter(new FileWriter(file));

writer.write("1 1 1 1 1 \n");
writer.write("2 2 2 2 2 \n");
writer.write("3 3 3 3 3 \n");
writer.write("4 4 4 4 4 \n");
writer.write("5 5 5 5 5");

writer.flush(); //Cria o conteúdo do arquivo.
writer.close(); //Fechando conexão e escrita do arquivo.

To read, an idea would be:

FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String data = null;
while((data = reader.readLine()) != null){
    System.out.println(data);
    //imprime o conteúdo, mas você poderia fazer outras
    //coisas com a variável data como salvar numa string que 
    //representa o arquivo etc.
}
fileReader.close();
reader.close();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.