Brandon Tao Brandon Tao - 24 days ago 8
Java Question

Java Overwrite file

public void saveList(Vector<Vector> table_data){
ArrayList<String> output_list = new ArrayList<String>();
for(int i=0;i<table_data.capacity();i++){
String temp="";
Vector tempVector = (Vector) table_data.elementAt(i);
tempVector.trimToSize();
for(int v=0;v<tempVector.capacity();v++){
temp+=((String)tempVector.elementAt(v))+" ";

}
temp = temp.trim();
System.out.println(temp);
output_list.add(temp);
}
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter(output_filename,false);
bw= new BufferedWriter(fw);
for(String i : output_list){
bw.write(i);
bw.newLine();
}

}
catch(FileNotFoundException e){}
finally{
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


Here is my code rewriting a file. There is a JButton calling this function every time I click it. It passes vector from JTable. The file should always be overwritten. But it actually only overwrites when i first click the button. What is the issue and how can I solve it?

Answer

You don't catch the IOException so this doesn't compile

try{
    fw = new FileWriteroutput_filename,false);
    bw= new BufferedWriter(fw);
    for(String i : output_list){
        bw.write(i);
        bw.newLine();
    }
}
catch(IOException e){}

In this sample and test code, I used a Scanner to save on "ENTER" a different array generated at the beginning. This key pressed is the same as your Button will do to write in the file.

public static void main(String[] args) {
    String[][] array = new String[3][3]; //My array of test
    for(int i = 0; i < 9; ++i){
        array[i/3][i%3] = "#" + i;
    }

    Scanner sc = new Scanner(System.in); //A scanner to way my input
    for(String[] tmp : array){
        System.out.print("Press ENTER to continue");
        sc.nextLine(); //I am read, press "ENTER" to write in file
        BufferedWriter bw = null;
        FileWriter fw = null;
        try{
            fw = new FileWriter("test.txt",false);
            bw= new BufferedWriter(fw);
            for(String s : tmp){
                bw.write(s);
                bw.newLine();
            }
        }
        catch(IOException e){}
        finally{
            if (bw != null) {
                try {
                    bw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

And the result is : First time, file is created with

#0
#1
#2

Second time, file is overriten with:

#3
#4
#5

and again a third time :

#6
#7
#8

Then the program stop.

Comments