Vya Dionchella
Vya Dionchella

Reputation: 11

Formatting Data When Writing to Text File (Java)

public static void writer(ArrayList<String> a)
{
    FileWriter file  = new FileWriter("text1.txt");
    for(int i=0; i<a.size(); i++)
    {
        if(i%2==0)
        {
            file.write(a, i+2, 300);
        }
        else 
        {
            System.out.printf("a.get(i, i+1,300));
            System.out.println();
        }
    }
}

I am trying to write formatted text to a .txt file using the file.write method. I would like to use a formatting technique similar to the "System.out.printf" command. I want the program above to do the same thing as the program below, except writing to a text file instead of the console. Any suggestions? The text(of varying lengths) must line itself up in two neat columns, each beginning at the same point. I cannot change the form of the input from a List of String objects. I am unfamiliar with BufferedOutputStream and pretty much any other "writing to text file" class, so if your solution involves that, please explain things a bit more thoroughly than normal. Thank you!

   public static void formatter(ArrayList<String> a)
{
    System.out.printf("%-15s", "Item:");
    System.out.printf("%1s", "Price:");
    System.out.println();
    for(int i=0; i<a.size(); i++)
    {
        if(i%2==0)
        {
            System.out.printf("%-15s",a.get(i));
        }
        else 
        {
            System.out.printf("$%1s",a.get(i));
            System.out.println();
        }
    }

Upvotes: 1

Views: 2832

Answers (1)

blm
blm

Reputation: 2446

The printf method is on the PrintStream class, so instead of new FileWriter("test1.txt") try new PrintStream("test1.txt"), the file.printf should work.

One way of discovering that on your own would be to look at the thing you want to do something the same as, i.e. System.out. You'll find that's a PrintStream, so then look at the PrintStream javadocs to discover how to open a file and return a PrintStream, which PrintStream itself conveniently provides a constructor for.

Upvotes: 1

Related Questions