1

I have a file with some info of a store and I want to sort it in another file like a table(in Excel).

the file :

001     Tablets                        5      3
002     pens                           4      1
005     Computeres                     3      0
003     Bages                          2      1
004     USB                            4      0

I write this code :

import java.util.*;
import java.io.*;

public class Sort {
public static void main(String [] args) throws IOException {
    FileInputStream fileinput = new FileInputStream("input.txt");
    FileOutputStream fileoutput = new FileOutputStream("output.txt");
    Scanner infile = new Scanner(fileinput);
    PrintWriter pw = new PrintWriter(fileoutput);
    int id, quantity, soldQuantity;
    String title;
    pw.println("ID\tTitle\t\t\tQuantity\tSoldQuantity");
    pw.println("");
    while(infile.hasNext()){
        id = infile.nextInt();
        title = infile.next();
        quantity = infile.nextInt();
        soldQuantity = infile.nextInt();
        pw.printf("%6d\t%s\t\t%d\t%d%n", id , title, quantity, soldQuantity);
    }
    infile.close();
    pw.close();
}
}

and I want it to look like this :

Code(ID)    Name            Quantity    SoldQuantity

     001    Tablets                5               3
     002    pens                   4               1
     005    Computeres             3               0
     003    Bages                  2               1
     004    USB                    4               0

my problem is the number of the quantity and sold quantity , it don't fit well . looks like this :

Code(ID)    Name            Quantity    SoldQuantity

     001    Tablets             5               3
     002    pens             4               1
     005    Computers             3               0
     003    Bags             2               1
     004    USB             4               0

The problem happens when the size of the name is different if there is a name bigger than "computers" , how can I handle it ?

Thanks

2
  • 1
    The way you want it to look like has nothing to do with sorting regarding any column, am I missing something? Commented Apr 19, 2014 at 3:08
  • Yes, I agree. Isn't sorting issue. Is a questions of look like. Commented Apr 19, 2014 at 3:14

4 Answers 4

5

Instead of using \t for spacing, also use a width modifier for your string:

pw.printf("%6d\t%30s%d\t%d%n", id, title, quantity, soldQuantity);

If you really want to ensure that everything lines up no matter how long the longest title is, you could find the length of the longest, add one, and paste the format string together using that.

Sign up to request clarification or add additional context in comments.

1 Comment

how about rewarding him for his help by accepting his answer?
1

See docs in doc

Sample:

Formatter formatter = new Formatter();
System.out.println(formatter.format("%10s %10s %10s", "Title1", "Title2", "Title3"));

for (int i = 0; i < 10; i++) {
        String row = "info" + i;
        System.out.println(formatter.format("%10s %10s %10s", row, row, row));
}

Comments

0

Create a method that returns spaces based on length of item in Name column.

public String getSpaces(int len){
   int num = 23-len;
   char[] chars = new char[num];
   Arrays.fill(chars, ' ');
   return new String(chars);
}

Now do this to get spaces after title:

getSpaces(title.length);

Hope this helps

Comments

0

uniVocity-parsers has a Fixed-width parser/writer which you should use instead of trying to write your own.

You can even use a java bean with annotations. Here's an example:

class TestBean {

// if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
@NullString(nulls = { "?", "-" })
// if a value resolves to null, it will be converted to the String "0".
@Parsed(defaultNullRead = "0")
private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.
// In this case, IntegerConversion will be used.
// The attribute name will be matched against the column header in the file automatically.

@Trim
@LowerCase
// the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
@Parsed(index = 4)
private String comments;

// you can also explicitly give the name of a column in the file.
@Parsed(field = "amount")
private BigDecimal amount;

@Trim
@LowerCase
// values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
@BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
@Parsed
private Boolean pending;

Let's write a fixed-width file with our TestBean:

FixedWidthFieldLengths lengths = new FixedWidthFieldLengths(10, 10, 35, 10, 40);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(lengths);

// Any null values will be written as ?
settings.setNullValue("?");

// Creates a BeanWriterProcessor that handles annotated fields in the TestBean class.
settings.setRowWriterProcessor(new BeanWriterProcessor<TestBean>(TestBean.class));

// Sets the file headers so the writer knows the correct order when writing values taken from a TestBean instance
settings.setHeaders("amount", "pending", "date", "quantity", "comments");

// Creates a writer with the above settings;
FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings);

// Writes the headers specified in the settings
writer.writeHeaders();

// writes a fixed width row with empty values (as nothing was set in the TestBean instance).
writer.processRecord(new TestBean());

TestBean bean = new TestBean();
bean.setAmount(new BigDecimal("500.33"));
bean.setComments("Blah,blah");
bean.setPending(false);
bean.setQuantity(100);

// writes a Fixed Width row with the values set in "bean". Notice that there's no annotated
// attribute for the "date" column, so it will just be null (an then converted to ?, as we have settings.setNullValue("?");)
writer.processRecord(bean);

// you can still write rows passing in its values directly.
writer.writeRow(BigDecimal.ONE, true, "1990-01-10", 3, null);

Output:

amount    pending   date                               quantity  comments
?         ?         ?                                  ?         ?
500.33    no        ?                                  100       blah,blah
1         true      1990-01-10                         3         ?

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.