I try to implement a text entry from JEditorPane . When reading text using the .getText() method and then writing to the txt file, the Cyrillic alphabet is converted into characters like "в" . How can this be overcome?

Full text class:

 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.nio.charset.StandardCharsets; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.Size2DSyntax; import javax.print.attribute.standard.MediaPrintableArea; import javax.print.attribute.standard.MediaSize; import javax.swing.*; public class PreviewPrinting extends JDialog{ private static final long serialVersionUID = 804726784085628551L; JEditorPane previewPane; JScrollPane scrlPane; JButton printBtn; JButton saveBtn; JButton cancelBtn; JPanel mainPanel; private String text = ""; //Конструктор. Принимает аргументы для подстановки в шаблон .html. public PreviewPrinting(String[] veriables){ this.setSize(590, 490); this.setModal(true); this.setTitle("Предпросмотр и печать документа"); this.setLocationRelativeTo(null); this.setResizable(false); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); //Передаём текст для отображения и печати используя один из шаблонов. try{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("report.htm"), StandardCharsets.UTF_8)); while (br.ready()){ text+=br.readLine(); } br.close(); } catch (Exception readEx) { JOptionPane.showMessageDialog(null, "Файл шаблона не найден!", "Ошибка!", JOptionPane.ERROR_MESSAGE); } /**/ /**/ /**/ /**/ /*Здесь должна быть обработка подстановки данных veriables в считанный шаблон.*/ /**/ /**/ /**/ /**/ //Создаём компоненты окна и обработки событий нажатия кнопок. printBtn = new JButton("<html><b><u>Печать</u></b></html>"); printBtn.setBounds(495, 372, 80, 20); printBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { try { //Устанавливаем размеры полей по умолчанию. PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); attrs.add(new MediaPrintableArea(10, 10, MediaSize.ISO.A4.getX( Size2DSyntax.MM ) - 20, MediaSize.ISO.A4.getY( Size2DSyntax.MM ) - 20, Size2DSyntax.MM)); //Печатаем. previewPane.print(null, null, true, null, attrs, true); } catch (Exception printEx) { JOptionPane.showMessageDialog(null, printEx.getMessage(), "Ошибка!", JOptionPane.ERROR_MESSAGE); } dispose(); } }); saveBtn = new JButton("Сохранить"); saveBtn.setBounds(495, 402, 80, 20); saveBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = previewPane.getText(); JFileChooser fc = new JFileChooser(); System.out.println(text); if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){ try{ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fc.getSelectedFile()), StandardCharsets.UTF_8)); bw.write(text); bw.close(); } catch (Exception saveEx) { JOptionPane.showMessageDialog(null, saveEx.getMessage(), "Ошибка!", JOptionPane.ERROR_MESSAGE); } } } }); cancelBtn = new JButton("Отмена"); cancelBtn.setBounds(495, 432, 80, 20); cancelBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { dispose(); } }); previewPane = new JEditorPane("text/html", text); previewPane.setEditable(false); scrlPane = new JScrollPane(previewPane); scrlPane.setBounds(10, 10, 480, 443); mainPanel = new JPanel(); mainPanel.setLayout(null); mainPanel.add(scrlPane); mainPanel.add(printBtn); mainPanel.add(saveBtn); mainPanel.add(cancelBtn); this.getContentPane().add(mainPanel); } } 
  • one
    But you can get a fragment of the code for receiving text and writing - Artem Konovalov
  • Sorry, I still do not understand how to add the code. Added to the text of the question. - Artik
  • one
    Apparently the encoding is not the same, but which one do you choose when opening a file? - Artem Konovalov
  • There the meaning is this: there is an html file, I open it and read the text. This text is processed and transmitted to JEditorPane ("text / html", text). At this stage, everything is OK. Next, this text must be saved in a txt file. This is where the shoals climbs. The file itself is ANSI-encoded. Tried to change, does not help. I tried to put CP1251 and UTF8 encoding when reading a file. Does not help. - Artik

2 answers 2

It is difficult to say what exactly the problem is, I put a quick code on it. The file should be saved in utf-8.

 public class Solution extends JFrame { private Solution() { super("title"); JEditorPane pane = new JEditorPane(); pane.setEditable(true); pane.setContentType("text/html"); pane.setText("<h2>hello world</h2>"); getContentPane().add(new JScrollPane(pane), "Center"); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; getContentPane().add(panel, "South"); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); JButton saveButton = new JButton("Save"); saveButton.addActionListener(e -> { String text = pane.getText(); JFileChooser fc = new JFileChooser(); System.out.println(text); if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fc.getSelectedFile()), StandardCharsets.UTF_8))) { bw.write(text); } catch (Exception saveEx) { JOptionPane.showMessageDialog(null, saveEx.getMessage(), "Ошибка!", JOptionPane.ERROR_MESSAGE); } } }); panel.add(Box.createVerticalStrut(10)); panel.add(saveButton); panel.add(Box.createVerticalGlue()); panel.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); getContentPane().add(panel, "East"); } public static void main(String[] args) { JFrame f = new Solution(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); f.setSize(500, 400); f.setVisible(true); }} 
  • I tried to add StandardCharsets.UTF_8. Did not help. I specifically added the line System.out.println (text); for control. Crackers are also displayed in the console. That is, the problem begins already when reading text from the JEditorPane (in the String line text = pane.getText ();) - Artik
  • @Artik and in what encoding html file? Is it in jeditpane normally displayed? - Artem Konovalov
  • That's the thing, in JEditPane it is displayed normally. ANSI file. And when reading text from JEditPane, it produces & # ... characters. - Artik
  • @Artik is a problem in HTMLWriter in the output() method, all characters whose code exceeds 127 converts to & # symbol_code. To avoid this, either redefine it or change text/html to text - Artem Konovalov
  • The whole thing is that I need the html markup. I want to use it to create templates for printing, which will be substituted data values. - Artik

Try this design

 String text = new String(previewPane.getText().getBytes("UTF-8")); 

PS Conducted an experiment screen from my computer Please give me the full code of your application.

  • I also tried it. Does not help. - Artik
  • So stop, how do you read the file? - plesser
  • I added the full text to the question. True, I did not understand how beautifully insert the text of the code. - Artik