Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings are not written to a new line

Following snippet attempts to write the name of directories and files present in some directory to a text file.Each name should be written to a separate line.Instead it prints each name on the same line. Why is it so ?

        try {
        File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
        FileWriter writer = new FileWriter(listFile,true);
        Iterator iterator = directoryList.iterator();
        while(iterator.hasNext()) {
            writer.write((String)iterator.next());
            writer.write("\n"); // Did this so each name is on a new line
        }
        writer.close();
    }catch(Exception exc) {
        exc.printStackTrace();
    }

output:

enter image description here

Where am i making a mistake ?

like image 995
Suhail Gupta Avatar asked Jan 25 '26 20:01

Suhail Gupta


1 Answers

Whenver you need textual formatting always use PrintWriter.
The right way of doing is to wrap the writer inside a PrintWriter and use println() method, like:

PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
like image 173
Suraj Chandran Avatar answered Jan 28 '26 08:01

Suraj Chandran