public void saveFile(File file) { try { PrintWriter out = new PrintWriter( new FileOutputStream(file),true); Vector line = null; int i =0; while (i < data.size()) { line = (Vector)data.get(i); System.out.println("What is line ? " +line); i++; System.out.println("Before write "); out.println(line); System.out.println("After write "); } out.close(); } Here is the result of the line:System.out.println("What is line ? " +line);
[Name , adres , Zip code, City , Phone , email]
I do not want to write the [ ] to my output file, because they appear in my table when i read the file again.
YOu have two options. 1. Before writing your vector content to file/database strip the brackets as follows.
Vector v = new Vector ( );
// add element s here
..................
// Get the string representation of vector with []
String str = v.toString()
// Now stript the [ ]
str = str.substring(1, str.length() -1 );
// Now store str in database and str won't have []
2. Create your own Vector class as MVector in following example. Override toString method of MVector and return the string representation of Vector stripping the brackets. Choose one of the above methods, which suits your requirement. Thanks Kishori //////////////////////////////Test.java /////
import java.util.* ;
class MVector extends Vector {
public String toString() {
String str = super.toString() ;
str = str.substring ( 1, str.length() - 1 ) ;
return str;
}
}
class Test {
publicstaticvoid main ( String[] args ) throws Exception {
MVector v = new MVector() ;
v.add ( "Kishori" ) ;
v.add ( "Shetty" ) ;
v.add ( "Hello" ) ;
System.out.println ( v ) ;
}
}
The toString() of vector class embeds a comma and a space between two elements. If you want to take out that space and leave comma there then you have two options. 1. When you are overriding toString() method of Vector class, loop thru all elements and then construct the string as follows.
class MVector extends Vector {
public String toString() {
StringBuffer sb = new StringBuffer();
int total = this.size() ;
for (int i = 0; i < total ; i++) {
sb.append( String.valueOf ( this.get( i ) ) ) ;
if ( i < total - 1 ) {
// Append only a comma
sb.append(",");
}
}
return sb.toString();
}
}
2. Write a method in your class thaat takes a Vector as an argument and returns its string representation in the format you want as:
public String getString ( Vector v ) {
if ( v == null ) {
return "null" ;
}
StringBuffer sb = new StringBuffer();
// Get the total no of elements in vector
int total = v.size() ;
// Loop thru all elements
for ( int i = 0; i < total ; i++ ) {
// Append the element in string buffer
sb.append( String.valueOf ( v.get(i))) ;
if ( i < total - 1 ) {
// Append only a comma
sb.append(",");
}
}
return sb.toString();
}