0

i am doing a sample program where i need to get the values from database as example candidatename and to write a .txt file and this part is ok for me. my problem is in .txt file the name value is fixed length so i need to add some 0 before the name to fulfil that condition . for example my name lenght in .txt file is 10 char and if my name is "amar" then i need to add some 0 before the name as "0000000amar". i am attaching my code bellow

  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();

} }

Please help

ASADUL
  • 308
  • 5
  • 17

1 Answers1

1
String str = "amar";
str = String.format("%11s", str).replace(' ', '0');
System.out.println(str); // 0000000amar
Timuçin
  • 4,653
  • 3
  • 25
  • 34