Java 输出文件格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5825627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java output file formatting
提问by Brendan Lesniak
I am having a bit of trouble formatting an output file for myself to be easily readable. I am trying to output the file such as:
我在为自己格式化输出文件以使其易于阅读时遇到了一些麻烦。我正在尝试输出文件,例如:
Name of School Size of School
-------------- --------------
Blblah blah 1300
Blah blah blah 11300
Blah blah blah asdf 14220
Blah bblah 1300
but am having trouble. Currently I am using the following code to get the following output:
但我遇到了麻烦。目前我正在使用以下代码来获得以下输出:
File file1 = new File("src\sortedInt.txt");
Formatter fmt = new Formatter(file1);
HelperMethods.quickSortStudents(colleges, 0, colleges.length - 1);
for(int i = 0; i < colleges.length; i++)
{
fmt.format(colleges[i].nameOfSchool + "%20d" + "\n", (int)colleges[i].numOfStudents);
fmt.flush();
}
which gives me:
这给了我:
eastman school of music 800
clark university 1100
walla walla college 1100
drew 1200
juilliard 1200
Because I am just padding from the end of the college name. Is there anyway to pad the whole string so all the strings are a constant length?
因为我只是从大学名称的末尾填充。无论如何都要填充整个字符串,以便所有字符串的长度都是恒定的?
Thank you everyone for you help
谢谢大家的帮助
回答by Mac
Yep, output your college name left-justified and padded to a certain length, then output your number of student right-justified and padded to a certain length:
是的,输出你的大学名称左对齐并填充到一定长度,然后输出你的学生人数右对齐并填充到一定长度:
fmt.format("%-20s%10d\n", colleges[i].nameOfSchool, (int) colleges[i].numOfStudents);
回答by Iwan Luijks
You might want to add the name of the schools to be formatted too, as the following:
您可能还想添加要格式化的学校名称,如下所示:
fmt.format("%1s %1d\n", colleges[i].nameOfSchool, (int)colleges[i].numOfStudents);
The following link can give you more insight in formatting: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
以下链接可以让您更深入地了解格式:http: //download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html