当我将文本显示到我的文本区域时,我有一个文本编码问题。
问题是当有这样的字符:é à è
我在文本区用? ? ?
代替
下面是读取我的文件的部分代码:
private void importerActionPerformed(java.awt.event.ActionEvent evt) {
jTabbedPane1.setSelectedIndex(0);
try {
JFileChooser explorer = new JFileChooser(chemin);
int answer = explorer.showOpenDialog(this);
if (answer == JFileChooser.APPROVE_OPTION) {
chemin = explorer.getCurrentDirectory().getAbsolutePath();
String name = explorer.getSelectedFile().getCanonicalPath();
System.out.println("name : "+name);
texte.setText("");
File file = new File(name);
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String result = in.readUTF();
texte.setText(result);
in.close();
System.out.println("Erreur la");
} catch (IOException e) {
DataInputStream in = new DataInputStream(new FileInputStream(file));
String result = null;
result = "";
byte[] buff = new byte[2048];
int read = in.read(buff, 0, 2048);
while (read >= 0) {
String substr = new String(buff, 0, read);
result += substr;
read = in.read(buff, 0, 2048);
}
// System.out.println(result);
Charset charset = Charset.forName("UTF-8");
result = charset.decode(charset.encode(result)).toString();
texte.setText(result);
in.close();
//System.out.println("Erreur la2");
}
}
} catch (Exception err) {
JOptionPane.showMessageDialog(this, "Erreur lors du chargement du fichier", "Error", JOptionPane.WARNING_MESSAGE);
}
}
我的textarea是:texte.setText(result);
你知道吗?
如果您的文件编码是UTF-8,那么只需像这样读取
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
texte.setText(result);
字符集。Encode方法需要unicode格式的字符串。事实上,java中的所有字符串都应该是unicode (utf16)。这样做
String substr = new String(buff, 0, read, "UTF-8");
并删除所有字符集。编码/解码代码。
您的String substr = new String(buff, 0, read);
行应该是
String substr = new String(buff, 0, read,"UTF-8");
构造函数String(byte[] bytes, int offset, int length)
通过使用平台的默认字符集解码指定的字节子数组来构造一个新的String。