There is such code:

import java.io.BufferedReader; import java.io.InputStreamReader; public class PingIP { public static void runSystemCommand(String command) { try { Process p = Runtime.getRuntime().exec(command); BufferedReader inputStream = new BufferedReader( new InputStreamReader(p.getInputStream())); String s = ""; // reading output stream of the command while ((s = inputStream.readLine()) != null) { System.out.println(s); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String ip = "google.com"; runSystemCommand("ping " + ip); } } 

Saved the file in different encodings from vs studio code. Saving in Cyrillic 1251 in the screenshot. How to fix the encoding? Cmd displays ping responses in Russian by default. Maybe you can change the English, but it is in the background, I would like to in Russian.

enter image description here

  • Have you used the InputStreamReader constructor, which takes the 2nd Charset parameter? - Andrew Bystrov
  • Try this: new InputStreamReader(p.getInputStream(), "UTF-8")); , as Andrey Bystrov suggests - MrFylypenko
  • @AndrewBystrow solid question marks instead of Russian characters - aaa
  • @MrFylypenko solid question marks instead of Russian characters - aaa
  • I tried various combinations of encodings and encodings while saving - without result - aaa

1 answer 1

Programs that are designed for use in Windows in the console mode, for historical reasons, use the CP866 encoding used for output in DOS. Java considers strings to contain Unicode. In other words, the stream that you receive from process p contains CP866, and you treat it as if it contains Unicode.
Open the stream like this:

  BufferedReader inputStream = new BufferedReader(new InputStreamReader( p.getInputStream(), Charset.forName("CP866"))); 

and everything will be fine.

  • It even worked like this new InputStreamReader (p.getInputStream (), "CP866")); - aaa
  • Is there a difference between? - aaa
  • No, in principle. These are just different overloaded versions of the constructor, one takes a String with the name of an encoding as an argument (as in your example), and the other takes the encoding itself (as in my example). The first option is laconic, but the second option allows you to use the encoding obtained from somewhere without even knowing its name. By the result in this case they are equivalent. - m. vokhm
  • @ thank you to you - aaa
  • one
    Although this is not directly related to the issue, I have the following remarks: 1). Make a definition of the encoding depending on the system. Java is a multi-platform environment, and if you run this code in Linux, again you will get unreadable characters; 2). If you use Java 7+, use try-with-resources when working with streams, this will avoid resource leaks and close the streams correctly - lospejos