简体   繁体   中英

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.

使用p.print而不是p.println println在您的示例中的打印后添加了一个 '[l]i[n]e'-break 虽然您 cna 只是没有在末尾放置“\\n”,这是字符串表示法[n] 新行

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM