Help please, use writeInt to write the length of the array in a text document, but the number is not displayed in the notebook (the symbol of an empty square)

 public static void outputPupils(Pupil v, OutputStream out) throws IOException { DataOutputStream stream = new DataOutputStream(out); stream.writeInt(v.getSecn().length()); stream.close(); } 

Main:

  OutputStream fout = new FileOutputStream("C:\\Users\\Sfroe\\Desktop\\output.txt"); Pupils.outputPupils(sb, fout); 

getSecn returns the student's last name.

  • So many questions. Why in the text writeInt , and in the code writeByte ? What does v.getSecn.length() return? What did you expect to see in the file? - default locale
  • I apologize, the code should be writeInt, on assignment I need to write the length of the last name to the file before writing it directly (this returns v.getSecn.length ()) - sfroe
  • 2
    OutputStream is intended for writing bytes in binary mode. Files recorded in this mode cannot be read as text, what are you trying to do by opening it in a text editor. - Sergey Gornostaev
  • I mistakenly thought that writeInt was intended to write a number. Here is the statement of the assignment - write the student information to a byte stream (use DataOutputStream) public static void output Pupil (Pupil v, OutputStream out), - sfroe

2 answers 2

DataOutputStream.writeInt writes a byte number representation to the stream. For example, if you pass 10 to a method, four bytes will be written: three zero, and the last one is 00001010 .

In order for a number to be readable in a text editor, it is necessary that symbols be written in the file. For example, for 10, the characters "1" and "0" should be encoded. This can be writeBytes through writeBytes by converting the number to a string:

  stream.writeBytes(v.getSecn().length()+""); 
  • Can you explain in what cases use writeInt? - sfroe
  • @sfroe Data written using writeInt cannot be read as text, but can be read via DataInputStream.readInt . It is not always important to read the file yourself, you can write / transfer data in binary format. - default locale

In the parameter false - the file will be overwritten

 public static void outputPupils(Pupil v, String path) throws IOException { FileWriter fout = new FileWriter(path, false); writer.write(v.getSecn().length()); writer.flush(); } 

Main:

  String path = "ваш путь"; Pupils.outputPupils(sb, path);