How to present the correct accent on the return of cmd?

Asked

Viewed 1,828 times

5

Considering a method to list files from a folder using ProcessBuilder I have the incorrect return of the accented words.

Code

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

public class TesteCMD {

  public static void main(String[] args) throws Exception {
    LinkedHashSet<String> comandos = new LinkedHashSet<>();
    TesteCMD cmd = new TesteCMD();

    comandos.add("cd C:/Vídeos/Filmes");
    comandos.add("dir /b");

    System.out.println(cmd.executar(comandos.toArray(new String[comandos.size()])));
  }

  public String executar(String... comandos) {
    StringBuilder saida = new StringBuilder();
    BufferedReader leitor;
    ProcessBuilder processos;
    Process processo;
    String linha;

    try {
      processos = new ProcessBuilder("cmd.exe", "/c", String.join(" && ", comandos));
      processo = processos.start();
      processo.waitFor();
      leitor = new BufferedReader(new InputStreamReader(processo.getInputStream()));

      while ((linha = leitor.readLine()) != null) {
        saida.append(linha).append("\n");
      }
    } catch (IOException | InterruptedException ex) {
      return ex.getMessage();
    }

    return saida.toString();
  }
}

Briefcase

inserir a descrição da imagem aqui

Exit

run:
A Viagem de Chihiro (2001)
Batman - The Dark Knight Returns (2012)
Contos de Terramar (2006)
From up on Poppy Hill (2011)
Lilo e Stitch (2002)
Man of Steel (2013)
Meu Amigo Totoro (1988)
Meus Vizinhos os Yamadas (1999)
Nausica� do Vale do Vento (1984)
O Castelo Animado (2004)
O Castelo no C�u (1986)
O Mundo dos Pequeninos (2010)
O Rei Le�o
O Reino dos Gatos (2002)
O Servi�o de Entregas da Kiki (1989)
Only Yesterday (1991)
Pom Poko (1994)
Ponyo (2008)
Porco Rosso (1992)
Princesa Mononoke (1997)
Shingeki no Kyojin (2013)
Sussuros do Cora��o (1995)
The Animatrix (2003)
The Matrix (1999)
T�mulo dos Vagalumes (1988)
UP - Altas Aventuras (2009)
V de Vingan�a (2005)
Vidas ao Vento (2013)

CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

I know there are other ways to list the files and that’s not the point. I would like to know how to resolve so that the return of my processes are accentuated correctly and also why this occurs.

I already tried to add the encoding (UTF-8, ISO-8859-1 and windows-1252) in the InputStreamReader but did not fix the problem.

Observing

I have tried with other commands, for example:

System.out.println(cmd.executar("@ECHO Teste acentuação"));

Results in:

run:
Teste acentua��o

CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

When it should be:

inserir a descrição da imagem aqui

1 answer

5


Use the command chcp to change the charset of the cmd.

For UTF-8 the code is 65001

The command to execute:

chcp 65001

I’m not sure where I could perform within those functions you’ve presented.

You can try the multi-command concatenator, the character &

System.out.println(cmd.executar("chcp 65001 & @ECHO Teste acentuação"))

Alternatively you can invoke an arquvio .bat. Example here: /a/105648/4793

To learn more about concatenating multiple commands and redirecting outputs: https://stackoverflow.com/questions/13719174/how-to-execute-multiple-commands-in-a-single-line

Printstream

Also try to change this section:

System.out.println(cmd.executar(comandos.toArray(new String[comandos.size()])));

For that:

PrintStream p = new PrintStream(System.out, true, "UTF-8");
p.println(cmd.executar(comandos.toArray(new String[comandos.size()])));

Encoding of the text editor

You may also have other reasons like the text editor. Check which encoding is saving the source editor.

Observing

If you are calling the JAVA script at the Windows prompt it may just be the prompt setting. Try:

chcp 65001
java /local/do/app/java.jar

Encoding 850

Also test code 850

PrintStream p = new PrintStream(System.out, true, "CP850");
p.println(cmd.executar(comandos.toArray(new String[comandos.size()])));

In that case, remove that command: chcp 65001 &





*Here I presented example for UTF-8. Make sure which charset you are using and apply the proper code.

  • It didn’t work. I made the call the following way chcp 65001 && @ECHO Teste acentuação and received the text P�gina de c�digo ativa: 65001 and Teste acentua��o. I’ve changed too InputStreamReader to read UTF-8

  • The difference between & and && is only if he will make the second instruction case the first of exit(1). But anyway I changed and continues without returning with the correct accent

  • Try using the Printstream class. I put example in the answer.

  • It didn’t work either. What worked was to do the InputStreamReader use the CP850

  • Would it be if I put the chcp 850 and the InputStreamReder for CP850 will work on any computer?

  • 1

    The default for Windows is code page 850. It should work well if the JAVA input and output are also in the default. The JAVA standard always expects 850 (in windows). The ideal is to detect automatically and provide manual adjustment option to the user.

  • Oops beauty, thank you for the reply

Show 2 more comments

Browser other questions tagged

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