提问人:Monita Shinkar 提问时间:9/5/2023 最后编辑:PinoMonita Shinkar 更新时间:9/5/2023 访问量:112
如何在 java 中从文本文件中读取和打印印地语字符
How to read and print Hindi characters from text file in java
问:
- 文本文件为:
MHEM CLASS 1
MHEM CLASS 2
MHEM CLASS 3
MHEM CLASS 4
MHEM CLASS 5
कक्षा 4 रिमझिम
कक्षा 5 रिमझिम
- 我需要阅读字符的
कक्षा 4 रिमझिम
कक्षा 5 रिमझिम
- 下拉列表显示印地语字符的框,控制台显示问号:
????? 4 ??????
我试过了
PrintStream out = new PrintStream(System.out, true, UTF_8);
答:
0赞
linden
9/5/2023
#1
我在这里没有看到任何问题。
让我们继续你的代码,并确保它以以下方式编写:
PrintStream out = new PrintStream(System.out, true, "UTF_8"); <-- Encoding goes in string here.
String line;
while ((line = br.readLine()) != null) {
out.println(line);
}
这里 br 是你的 BufferedReader,它是你的 inputStreamReader 的重载构造函数。(输入TXT文件)
在我的机器上测试了这个设置,效果很好。
让我知道这是否有效。或者您需要进一步的帮助。谢谢。
评论
0赞
skomisa
9/10/2023
你声称这“效果很好”,但你用 Swing 测试过吗?如果是这样,你的代码在哪里?OP 的问题不是关于一个简单的 Java 应用程序;它专门用于在使用 Swing 时在组合框中呈现印地语文本。
1赞
Pino
9/5/2023
#2
首先,阅读有关 Unicode 和 UTF-8 的内容。可能的来源是:
验证是否使用正确的字符集读取文本文件(如果文件是使用 UTF-8 创建的,则必须使用 UTF-8 读取它)。
在下拉列表中,使用支持整个 Unicode 字符集的字体。您可以使用 Windows' 来检查字体。
charmap.exe
使用 UTF-8 写入控制台是不够的:您必须确保控制台使用 Unicode。例如,请参阅:
评论
0赞
skomisa
9/10/2023
但是 OP 的问题是在 Swing 组合框中呈现文本。你的答案甚至没有提到 Swing!
0赞
Pino
9/10/2023
该问题与 Swing 和控制台有关。我回答的第 #3 点与 Swing 下拉列表有关,第 #4 点与控制台有关;点 #1 和 #2 是两者的先决条件。
0赞
DevilsHnd - 退した
9/5/2023
#3
另一种方法可以做到这一点。阅读代码中的注释:
public void loadComboItems(javax.swing.JComboBox combo, String filePath)
throws java.io.FileNotFoundException {
/* Make sure the supplied Combobox font is `SansSerif`
(or any other font that can handle UTF-8): */
combo.setFont(new java.awt.Font("sansserif", java.awt.Font.PLAIN, 12));
/*
===================================================================
== 'Make sure' the text file had been saved in `UTF-8` format!!! ==
===================================================================
*/
// Declare a new DefaultComboBoxModel:
javax.swing.DefaultComboBoxModel model = new javax.swing.DefaultComboBoxModel();
/* Read the text file. `Try With Resources` is used here
to auto-close the file and free resources once reading
has completed: */
try (java.util.Scanner reader = new java.util.Scanner(new java.io.FileInputStream(filePath), "UTF-8")) {
String line;
// Iterate through the file lines:
while (reader.hasNextLine()) {
line = reader.nextLine();
// Make sure the read in file line is not blank:
if (!line.isEmpty()) {
// Add the file line to model:
model.addElement(reader.nextLine());
}
}
// Set the new model to the supplied JComboBox:
combo.setModel(model);
/* Optional - Don't show any item selected within
the supplied JComboBox: */
combo.setSelectedIndex(-1);
}
}
如何使用上述方法:
try {
loadComboItems(jComboBox1, "ComboItems.txt");
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
评论
[Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding
public DefaultComboBoxModel<String> loadCombo(String path) throws IOException { return new DefaultComboBoxModel<String>(Files.lines(Path.of(path)).toArray(String[]::new));