Search code examples
javafilewriter

how to write from linkedlist to a text file using java


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

Solution

  • 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