Abh*_*yay 3 java string file-io utf
我DataOutputStream今天在Java 中使用它,但它给了我一个中文输出,这绝对不是我的预期......有人可以在代码中发现错误吗?
private void generateButtonActionPerformed(java.awt.event.ActionEvent evt) {
textToSet=" Student Information";
textToSet=textToSet+"\nName\t: "+TitleBox.getSelectedItem()+" "+FirstNameField.getText()+" "+LastNameField.getText();
textToSet=textToSet+"\nClass\t: "+ClassField.getText();
TextArea.setText(textToSet);
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
File f=new File("C:\\Users\\username\\Desktop\\ID Card.txt");
DataOutputStream fs=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
fs.writeUTF(textToSet);
Desktop d=Desktop.getDesktop();
d.open(f);
fs.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
TitleBox是JComboBox,FirstNameField,LastNameField,和ClassField是JTextField的.TextArea是一个JTextArea.
当我选择"先生" 在TitleBox,输入"Man"in FirstNameField,"Ly"in LastNameField和"7th"in ClassField,我得到输出:
Student Information
Name : Mr. Man Ly
Class : 7th
Run Code Online (Sandbox Code Playgroud)
在TextArea中,但是在文件IDCard.txt中,我得到了输出:
?†††?????????????›???????????
Run Code Online (Sandbox Code Playgroud)
textToSet是String公共范围内定义的变量......有人能指出我正确的方向吗?writeUTF()代码有问题吗?
该writeUTF方法包括标题数据(您所谓的中文字符),表示它要写入的字符串的长度(2个字节,所以0-65535).您只能用于readUTF正确读取数据,它不适用于一般文本编写.
只需使用常规BufferedWriter.write(String str)来编写文本.