0

I wrote this code to write the nodes of this linked list to a text file, but it won't work with FileWriter whenever I try it with System.out.println("n.ModelName");

 public void modName() throws IOException{
     PrintWriter outputStream = null;
     outputStream = new PrintWriter(new FileWriter("C:\\Users\\OsaMa\\Desktop\\Toyota.txt"));
     node n=head;

    while (n != null){
       if(n.Company.equalsIgnoreCase("Toyota")){
          outputStream.println(n.ModelName);
           n=n.next;
       }
       else{
           n=n.next;
       }
        } 
    }
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

0

You need to explicitely call flush or close the outputstream to see the output in your file. So once you are done with writing the data to stream you just ask stream to flush the data to file like:

outputStream.flush();

Or if you close the stream like:

outputStream.close();

to close the stream and flush the data to file.

Reason you see output when you use sysout is internally does the following:

if (autoFlush)
    out.flush();

If you want the same functionality then define your PrintWriter as:

outputStream = new PrintWriter(new FileWriter("C:\\Users\\OsaMa\\Desktop\\Toyota.txt"), true);//set auto flush on
                                                                                        ^^^^^
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Try this

public void modName() throws IOException{

     PrintWriter outputStream = null;
     outputStream = new PrintWriter("C:\\Users\\OsaMa\\Desktop\\Toyota.txt","UTF-8");
     node n=head;

    while (n != null){
       if(n.Company.equalsIgnoreCase("Toyota")){
          outputStream.println(n.ModelName);
           n=n.next;
       }
       else{
           n=n.next;
       }
        } 
    outputStream.close();

}

You need to close the stream once writing is done.

See Also

Community
  • 1
  • 1
RockAndRoll
  • 2,247
  • 2
  • 16
  • 35