用于从控制台输出到 JavaFX TextArea 的 UTF-8 编码 [英] UTF-8 encoding for output from Console to JavaFX TextArea

查看:73
本文介绍了用于从控制台输出到 JavaFX TextArea 的 UTF-8 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将控制台中的输出重定向到 JavaFX TextArea,我在这里遵循一个建议:JavaFX:将控制台输出重定向到 TextArea在 SceneBuilder 中创建

I want to redirect the output in Console to JavaFX TextArea, and I follow a suggestion here: JavaFX: Redirect console output to TextArea that is created in SceneBuilder

我尝试在 PrintStream() 中将字符集设置为 UTF-8,但是 它看起来不太好了.将字符集设置为 UTF-16 会有所改善,但 它仍然难以辨认.

I tried to set charset to UTF-8 in PrintStream(), but it does not look so well. Setting the charset to UTF-16 improves it a bit, but it is still illegible.

在 Eclipse IDE 中,控制台中假设的文本输出结果很好:

In Eclipse IDE, the supposed text output in Console turns out fine:

<代码> KHA科伊đầuphiênGIAO荻桑拒绝öMUC 23600điểm,胡维LUONG GIAO荻仲戈·恩盖đạt765 CO可漂,TUONGđươngkhoảng18054000đồng.

Controller.java

public class Controller {
    @FXML
    private Button button;

    public Button getButton() {
        return button;
    }

    @FXML
    private TextArea textArea;

    public TextArea getTextArea() {
        return textArea;
    }

    private PrintStream printStream;

    public PrintStream getPrintStream() {
        return printStream;
    }

    public void initialize() {
        textArea.setWrapText(true);
        printStream = new PrintStream(new UITextOutput(textArea), true, StandardCharsets.UTF_8);
    } // Encoding set to UTF-8

    public class UITextOutput extends OutputStream {
        private TextArea text;

        public UITextOutput(TextArea text) {
            this.text = text;
        }

        public void appendText(String valueOf) {
            Platform.runLater(() -> text.appendText(valueOf));
        }

        public void write(int b) throws IOException {
            appendText(String.valueOf((char) b));
        }
    }
}

UI.java

public class UI extends Application {
    @Override
    public void start(Stage stage) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
            Parent root = loader.load();
            Controller control = loader.getController();

            stage.setTitle("Title");
            stage.setScene(new Scene(root));
            stage.show();

            control.getButton().setOnAction(new EventHandler<ActionEvent>() {
                public void handle(ActionEvent event) {
                    try {
                        System.setOut(control.getPrintStream());
                        System.setErr(control.getPrintStream());
                        System.out.println(
                                "KHA khởi đầu phiên giao dịch sáng nay ở mức 23600 điểm, khối lượng giao dịch trong ngày đạt 765 cổ phiếu, tương đương khoảng 18054000 đồng.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

示例.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.BorderPane?>


<BorderPane prefHeight="339.0" prefWidth="468.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/11.0.1" fx:controller="main.Controller">
   <center>
      <TextArea fx:id="textArea" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
   </center>
   <right>
      <Button fx:id="button" mnemonicParsing="false" onAction="#getButton" text="Button" BorderPane.alignment="CENTER" />
   </right>
</BorderPane>

我还是 Java 新手,所以我不熟悉 PrintStream 或 OutputStream 的工作原理.请原谅我的无知.

I'm still new to Java so I'm unfamiliar to how exactly PrintStream or OutputStream works. Please excuse my ignorance.

感谢每一个建议.

推荐答案

我相信你的问题是由这段代码引起的:

I believe your problem is caused by this code:

public void write(int b) throws IOException {
    appendText(String.valueOf((char) b));
}

这是将每个单独的字节转换为一个字符.换句话说,它假设每个字符都由一个字节表示.这不一定是真的.某些编码,例如 UTF-8,可能使用多个字节来表示单个字符.如果他们希望能够表示超过 256 个字符,就必须这样做.

This is converting each individual byte into a character. In other words, it's assuming each character is represented by a single byte. That's not necessarily true. Some encodings, such as UTF-8, may use multiple bytes to represent a single character. They have to if they want to be able to represent more than 256 characters.

您需要正确解码传入的字节.与其自己尝试这样做,不如找到一种方法来使用诸如 BufferedReader 之类的东西.幸运的是,这可以通过 PipedInputStreamPipedOutputStream 实现.例如:

You'll need to properly decode the incoming bytes. Rather than trying to do this yourself it would be better to find a way to use something like BufferedReader. Luckily that's possible with PipedInputStream and PipedOutputStream. For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import static java.nio.charset.StandardCharsets.UTF_8;

public class Main extends Application {

  @Override
  public void start(Stage primaryStage) {
    TextArea area = new TextArea();
    area.setWrapText(true);

    redirectStandardOut(area);

    primaryStage.setScene(new Scene(area, 800, 600));
    primaryStage.show();

    System.out.println(
        "KHA khởi đầu phiên giao dịch sáng nay ở mức 23600 điểm, khối lượng giao dịch trong ngày đạt 765 cổ phiếu, tương đương khoảng 18054000 đồng.");
  }

  private void redirectStandardOut(TextArea area) {
    try {
      PipedInputStream in = new PipedInputStream();
      System.setOut(new PrintStream(new PipedOutputStream(in), true, UTF_8));

      Thread thread = new Thread(new StreamReader(in, area));
      thread.setDaemon(true);
      thread.start();
    } catch (IOException ex) {
      throw new UncheckedIOException(ex);
    }
  }

  private static class StreamReader implements Runnable {

    private final StringBuilder buffer = new StringBuilder();
    private boolean notify = true;

    private final BufferedReader reader;
    private final TextArea textArea;

    StreamReader(InputStream input, TextArea textArea) {
      this.reader = new BufferedReader(new InputStreamReader(input, UTF_8));
      this.textArea = textArea;
    }

    @Override
    public void run() {
      try (reader) {
        int charAsInt;
        while ((charAsInt = reader.read()) != -1) {
          synchronized (buffer) {
            buffer.append((char) charAsInt);
            if (notify) {
              notify = false;
              Platform.runLater(this::appendTextToTextArea);
            }
          }
        }
      } catch (IOException ex) {
        throw new UncheckedIOException(ex);
      }
    }

    private void appendTextToTextArea() {
      synchronized (buffer) {
        textArea.appendText(buffer.toString());
        buffer.delete(0, buffer.length());
        notify = true;
      }
    }
  }
}

上述 buffer 的使用是为了避免 JavaFX 应用程序线程被任务淹没.

The use of buffer above is an attempt to avoid flooding the JavaFX Application Thread with tasks.

您需要考虑的其他一些事项:

Some other things you need to take into consideration:

  • 由于您使用的是字符串文字,因此请确保使用 UTF-8 保存源文件并使用 -encoding UTF-8 编译代码.
  • 确保您在 TextArea 中使用的字体可以代表您想要的所有字符.
  • 可能您还需要使用 -Dfile.encoding=UTF-8 运行应用程序,但我不确定.我没有,但它仍然对我有用.
  • Since you're using a string literal, make sure you're both saving the source file with UTF-8 and compiling the code with -encoding UTF-8.
  • Make sure the font you use with the TextArea can represent all the characters you want it to.
  • It's possible you also need to run the application with -Dfile.encoding=UTF-8 but I'm not sure. I did not and it still worked for me.

这篇关于用于从控制台输出到 JavaFX TextArea 的 UTF-8 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆