简体   繁体   English

在Java中使用DataOutputStream可以提供一些中文输出

[英]Using DataOutputStream in Java gives some Chinese output

I was using DataOutputStream in Java today, but it gave me a Chinese output, that was absolutely NOT what I had expected... Can someone please spot the error in the code? 我今天在Java中使用DataOutputStream ,但它给了我一个中文输出,这绝对不是我的预期......有人可以在代码中发现错误吗?

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();
    }
}

TitleBox is a JComboBox , FirstNameField , LastNameField , and ClassField are JTextField 's. TitleBox是一个JComboBoxFirstNameFieldLastNameFieldClassFieldJTextField的。 TextArea is a JTextArea . TextArea是一个JTextArea

When I choose "Mr." 当我选择“先生” in TitleBox , type "Man" in FirstNameField , "Ly" in LastNameField and "7th" in ClassField , I get the output: TitleBox ,键入“人”在FirstNameField中,“Ly的” LastNameField和“7” ClassField ,我得到的输出:

       Student Information
Name    : Mr. Man Ly
Class   : 7th

in the TextArea, but in the file, IDCard.txt, I get the output: 在TextArea中,但是在文件IDCard.txt中,我得到了输出:

㠀†††匠畴敤瑮䤠普牯慭楴湯上浡॥›牍‮慍祌䌊慬獳㨉㜠桴

textToSet is a String variable defined in the public scope... Can someone point me in the right direction? textToSet是在公共范围中定义的String变量...有人能指出我正确的方向吗? Is there something wrong with the writeUTF() code? writeUTF()代码有问题吗?

The writeUTF method includes header data (your so called chinese characters) about how long a String it's going to write (2 bytes, so 0-65535). writeUTF方法包括头数据(你所谓的中文字符)关于它要写入的字符串的长度(2个字节,所以0-65535)。 You can only use readUTF to read that data properly, it's not meant for general text writing. 您只能使用readUTF正确读取数据,这不适用于一般文本编写。

Just use a regular BufferedWriter.write(String str) to write the text instead. 只需使用常规的BufferedWriter.write(String str)来编写文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM