我正在做一个示例程序,我需要从数据库中获取值作为示例候选名称并编写.txt文件,这部分对我来说没问题。我的问题是在.txt文件中,名称值是固定长度所以我需要在名称前添加一些0来满足该条件。例如,我的名字lenght在.txt文件中是10个字符,如果我的名字是“amar”,那么我需要在名称之前添加一些0作为“0000000amar”。我正在附上我的代码
package com.myapp.struts.Action;
public class Main {
public static final long RECORD_LENGTH = 100;
public static final String EMPTY_STRING = " ";
public static final String CRLF = "\n";
public static void main(String[] argv) throws Exception {
String a="";
String q="";
PrintWriter writer=null;
try
{
File file=new File("c:/report");
file.mkdirs();
Connection connection = mbjBaseDAO.getConnection();
Statement stmt = connection.createStatement();
String query="select candidate_name from online_application ";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
a=rs.getString("candidate_name");
int lenght=a.length();
System.out.println("lenght is"+lenght);
System.out.println(q);
writer=new PrintWriter("c:/report/challan.txt");
for(int i=0;i<10;i++)
{
writer.print(q+"\t");
if((i)==i)
{
writer.println();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
writer.flush();
writer.close();
}
}
public static String paddingRight(String source)
{
StringBuilder result = new StringBuilder(100);
if(source != null)
{
result.append(source);
for (int i = 0; i < RECORD_LENGTH - source.length(); i++)
{
result.append(EMPTY_STRING);
}
}
return result.toString();
} }
请帮忙
答案 0 :(得分:1)
String str = "amar";
str = String.format("%11s", str).replace(' ', '0');
System.out.println(str); // 0000000amar