Java覆盖文件

时间:2016-11-09 11:46:51

标签: java overwrite filewriter

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

这是我的代码重写文件。每次点击它时都会有一个JButton调用这个函数。它从JTable传递向量。应始终覆盖该文件。但它实际上只有在我第一次点击按钮时才会覆盖。问题是什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

你没有捕获IOException,所以这不会编译

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

在此示例和测试代码中,我使用扫描仪保存&#34; ENTER&#34;一开始生成的不同数组。按下此键与按钮在文件中写入的操作相同。

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

结果是: 第一次,使用

创建文件
#0
#1
#2

第二次,文件被覆盖:

#3
#4
#5

又是第三次:

#6
#7
#8

然后程序停止。