Search code examples
javaprintstream

How to use PrintStream to write to a text file without leaving any blank line between each row?


I'm doing a phone book project for my school homework assignment. What I have to do is to store information of each person into a text file and read it every time the program runs. However, every time it stores the information into the text file, it leaves a blank row between each line. That causes the program to read the blank row between when I need it to read information from the text file. That causes an error in my code.

I tried to use trim() in my reading function to skip the empty lines.

        while((currentLine= reader.readLine()) != null){
            String emptySpace = currentLine.trim();
            if(!emptySpace.equals("")) {
                ...
                ...
            }

This is my storing function

    public static void storePhoneBook (String FileName, Entry[] entryList, int totalEntry) throws Exception{
        PrintStream P = new PrintStream(FileName);
        for (int i=0; i < totalEntry; i++) {
            P.println(entryList[i].name + "\t" +
                    entryList [i].number + "\t" +
                    entryList [i].notes + "\n");
        }
        P.close();
        System.out.println("Phone book stored.");
    }

And what is written into the text file is this. They have blank space between each row.

Bill    419-536-1234     Bill Gates

JB  510-0114    Charlie's place

Jones   413-257-1234    Karen and Jason

wm  419-257-1234    Walmart

Can I write into a file without leaving any blank row between each line? The trim() function works in this instance but I don't think it's the most efficient way to do it.


Solution

  • use p.print instead of p.println the println adds a '[l]i[n]e'-break after the print in your example though you cna just not put "\n" at the end which is the string notation for a [n]ew line