I am using PrintWriter to write the input from the standard input to a file, here I am trying to create an ascii table in the text file, but there is no proper alignment of the table in the text file. Here is my code guys.

package code.practise.MyIdeas;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class WriteTextFile {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        String name, email;
        final String EMAIL_PATTERN = 
                "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        PrintWriter printwriter = new PrintWriter("User Details.txt");
        printwriter.println("+-----\t+-----\t+-----\t+");
        printwriter.println("|sno\t|Name\t|email\t|");
        printwriter.println("+-----\t+-----\t+-----\t+");
        try {
            A:for(int i = 1;;i++){                          
                System.out.println("Please enter the name:");
                System.out.println("You can quit by pressing enter key...");
                name = input.nextLine();
                System.out.println("Please enter the email:");
                email = input.nextLine();
                if(!email.matches(EMAIL_PATTERN)){                  
                    System.out.println("Please enter a valid email.\nThe details are not saved please start from the beginning.");
                    i--;
                    continue;
                }
                else
                {
                    printwriter.println("|"+i+")\t|"+name+"\t|"+email+"\t|");
                    printwriter.println("+-----\t+-----\t+-----\t+");
                }               
                for(;;){                
                    if(i>=1){                   
                        System.out.println("Do you wish to continue ?(y/n)");
                        String quit = input.nextLine();     
                        if(quit.equalsIgnoreCase("n"))break A;
                        else if (quit.equalsIgnoreCase("y")){
                            continue A;

                        }
                        else
                        {
                            System.out.println("Please enter either 'y' or 'n'");
                            continue;
                        }

                    }                   
                }
            }


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            input.close();
            printwriter.close();
        }
    }
}

And I am also attaching the created text file.

Thanks
Varun Krishna. P

Hve a look at System.out.printf - allows you to specify the format for what you print.

James Cherrill
I don't want it to show (format the string ) up in the console, I just want to format the output that appears in the text file.

Guys I am almost there, now I could not align the name and the email address. Here is my code

...
PrintWriter printwriter = new PrintWriter("User Details.txt");
printwriter.println("+---------+--------+---------+");
printwriter.printf("%-15s","|S.no     |Name    |Email    |\r\n");
printwriter.println("+---------+--------+---------+");
...
else
    {
        printwriter.printf("%-15s","|"+i+"        |"+name+"    |"+email+"     |\r\n");
        printwriter.printf("+---------+--------+---------+\r\n");                   
    }
...

And here is my text file, but the name and the email is not getting aligned properly.

That's heading ih the right direction, so here's your next hint!
In the first argument you put all the fixed text, and format instructions for all the variable parts. The remining parameters are then the values for the variable parts. eg - I want a table with vertical bars, and the first col right justified 8 wide, and the second col 10 wide left aligned. My format spec looks like

"|%8s|%-10s|\n"

try running a couple of examples...

System.out.printf("|%8s|%-10s|\n","I","love");
System.out.printf("|%8s|%-10s|\n","Dani","Web");

Thanks James
Your message was very helpful for me to learn things, good explanation keep it up. Here is my final completed code.

package code.practise.MyIdeas;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class WriteTextFile {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        String name, email;
        final String EMAIL_PATTERN = 
                "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        PrintWriter printwriter = new PrintWriter("User Details.txt");
        printwriter.println("+-----+--------------------+--------------------+");
        printwriter.printf("|%-5s|%-20s|%-20s|\r\n","S.no","Name","Email");
        printwriter.printf("+-----+--------------------+--------------------+\r\n");
        try {
            A:for(int i = 1;;i++){                  
                System.out.println("Please enter the name:");
//              System.out.println("You can quit by pressing enter key...");
                name = input.nextLine();
                System.out.println("Please enter the email:");
                email = input.nextLine();
                if(!email.matches(EMAIL_PATTERN)){                  
                    System.out.println("Please enter a valid email.\nThe details are not saved please start from the beginning.");
                    i--;
//                  break;
                    continue;
                }
                else
                {
                    printwriter.printf("|%5s|%20s|%20s|\r\n",i,name,email);
                    printwriter.printf("+-----+--------------------+--------------------+\r\n");                    
                }


                for(;;){                
                    if(i>=1){                   
                        System.out.println("Do you wish to continue ?(y/n)");
                        String quit = input.nextLine();     
                        if(quit.equalsIgnoreCase("n"))break A;
                        else if (quit.equalsIgnoreCase("y")){
                            continue A;

                        }
                        else
                        {
                            System.out.println("Please enter either 'y' or 'n'");
                            continue;
                        }

                    }                   
                }
            }


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            input.close();
            printwriter.close();
        }
    }

}

And here is my formatted text file.
Thanks
Varun Krishna. P

James and others
I have one more question though it is not related with alignment thing. I would like to track/detect the [esc] or [ctrl] + q key press in this console application. I am thinking to replace System.out.println("Do you wish to continue ?(y/n)"); with a code that could detect the [esc] or [ctrl]+ q key.

Sorry, I've literally never used the console in a real application, so I can't help.

One small suggestion: you have the same format string twice in the code (lines 17 and 34). That's the kind of thung that drives you mad when you (or someone else) are trying to change that code later. Much better to declare it once
static final String TABLE_FORMAT = "|%-5s|%-20s|%-20s|\r\n";
then use that for both the headings and the data, which will therefore always match.

James
I didn't notice the commonlity in line 17 and 34 good catch. I'll keep that in mind.

You are using Scanner class to accept an input (nextLine()), so you could simply test what the input would be. So what you may do is to convert the input String to bytes. If I remember correctly, the esc key gives you a byte array length of 1 with value of 27 inside. So you could check if the input value (after converted to byte array using getBytes() has size of 1 and the value inside is 27. Though, the user still has to press Enter key so the program will accept the value (for nextLine()). However, Ctrl+<any key> does not seem to be working for Java in the console...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.