有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java覆盖文件

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) 个答案

  1. # 1 楼答案

    你没有捕捉到IOException,所以无法编译

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

    在这个示例和测试代码中,我使用了一个扫描器在“输入”时保存了一个在开始时生成的不同数组。按下此键与在文件中写入的按钮相同

    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
    

    然后程序停止