简体   繁体   中英

String formatting in java. What does this mean?

I see this code and I'm wondering how many bytes it takes up:

// Create a PrintWriter by wrapping it around a FileWriter
PrintWriter output = new PrintWriter( new FileWriter( f, true) ); 
output.printf( "%-8s %-15s %10.2f %n", "P-102", "PartNumber102", 8.25 );
output.printf( "%-8s %-15s %10.2f %n", "P-103", "PartNumber103", 12.15 );
output.close();

How many bytes will `P-102 take up? It seems like it only has 5 characters so 5 bytes right? But what does the 8 mean? I think the dash is left justified and the s is a string... but what does the 8 mean?

Same thing for PartNumber103 which has 13 characters so 13 bytes? Why does it seem to take up 15 bytes?

You should read the documentation.

The format specifiers which do not correspond to arguments have the following syntax:

  %[flags][width]conversion 

The following table summarizes the supported flags. y means the flag is supported for the indicated argument types.

Flag

'-' The result will be left-justified.

Width

The width is the minimum number of characters to be written to the output.

So - means left justified, and the width is 8, so at least 8 characters but maybe more. The extra characters you are seeing may be coming from the width, as extra spaces will be added to pad out the result. Don't forget to count the spaces around the thing you are printing too. There's a hard coded space in front of the string, and one after it as well.

While UCS16 and other encodings are a possible answer here, all your output appears to be in the ASCII range so that's probably not the answer in this case.

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