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?
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. TextArea is a JTextArea.
When I choose "Mr." in TitleBox, type "Man" in FirstNameField, "Ly" in LastNameField and "7th" in ClassField, I get the output:
Student Information
Name : Mr. Man Ly
Class : 7th
in the TextArea, but in the file, IDCard.txt, I get the output:
㠀†††匠畴敤瑮䤠普牯慭楴湯上浡॥›牍慍祌䌊慬獳㨉㜠桴
textToSet is a String variable defined in the public scope... Can someone point me in the right direction? Is there something wrong with the writeUTF() code?
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). You can only use readUTF to read that data properly, it's not meant for general text writing.
Just use a regular BufferedWriter.write(String str) to write the text instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With