Search code examples
javaarraysnewlinefileoutputstream

how to make a new line on tex file for FileOutputStream


How can I create a new line for each loop? My program keeps on displaying everything in a single line... or how can I set a diff class to write data from arrays

static void writetofile(studentClass[] students)
   {
       try(DataOutputStream str= new DataOutputStream(new FileOutputStream("new.txt"))  )
     {

      for(int i=0;i<students.length;i++)
      {
         str.writeBytes(students[i].getStudentFname()+", ");
         str.writeBytes(students[i].getStudentLname()+" ");
         str.writeBytes(Integer.toString(students[i].getTestSore()));
         str.writeBytes(" ");
         str.writeChar(students[i].getGrade());
         str.writeBytes("\n");


      }
     }
     catch(Exception e)
     {
         System.out.println("Error");
     }
   }

Solution

  • Don't use DataOutputStream to write a text file. Use a Writer.

    Javadoc of DataOutputStream says:

    A DataOutputStream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a DataInputStream to read the data back in.

    It is for writing Java primitive types in a portable binary format. Not for writing a text file.

    A Writer however:

    Abstract class for writing to character streams.

    To help print newlines, use a PrintWriter:

    Prints formatted representations of objects to a text-output stream.

    Then the println() method will write the correct line terminator for you.

    So, your code should be:

    try (PrintWriter out = new PrintWriter(new FileWriter("new.txt")))
    {
        for (Student student : students)
        {
            out.println(student.getStudentFname() + ", " +
                        student.getStudentLname() + " " +
                        student.getTestSore() + " " +
                        student.getGrade());
        }
    }
    

    You can so use the formatting version, printf():

    try (PrintWriter out = new PrintWriter(new FileWriter("new.txt"))) {
        for (Student student : students)
            out.printf("%s, %s %d %c%n",
                       student.getStudentFname(),
                       student.getStudentLname(),
                       student.getTestSore(),
                       student.getGrade());
    }