4

我使用 FileWriter 和 BufferWriter 写入文件。创建了文件“test.txt”,但里面没有写入任何内容。

该文件应该写在我的按钮的 ActionEvent 中。这就是原因吗?

那是我的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;  
import java.util.UUID;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

class Cadre_fenetreA2 extends JFrame            
{
    JLabel phrase = new JLabel("Veuillez indiquer le nom de chaque groupe de generalisation pour chaque Niveau");
    JButton boutonOK = new JButton ("OK");
    public Cadre_fenetreA2 (String nom,int X, int Y, int lo, int la, int Na, int [] nbGrpGen,int maxnbGrpGen, File file)        
    {
        super(nom);                     
        setBounds(X,Y,lo,la);       
        setVisible(true);                   


        JTextField[][] allField = new JTextField [Na][maxnbGrpGen];
        JLabel phrases[] = new JLabel [Na];
        String[][] nomGrpGen = new String [Na][maxnbGrpGen];



        setLayout(null);
        for(int i = 0;i < Na;i++)
        {
            for(int j = 0;j<nbGrpGen[i];j++)
            {
                String uuid = UUID.randomUUID().toString();

                 allField[i][j] = new JTextField(uuid.substring(0,8));
                 allField[i][j].setBounds(150+j * 60, 75 + i * 25, 50, 20);
                 add(allField[i][j]);
            }

           phrases[i] = new JLabel("Niveau "+String.valueOf(i+1));
           phrases[i].setBounds(5, 75 + i * 25, 200, 20);

           add( phrases[i]);
        }
        phrase.setBounds(0,0,1000,50);
        add(phrase);
        boutonOK.setBounds(250+maxnbGrpGen*50,25*(Na),60,60);
        add(boutonOK);
        boutonOK.addActionListener(new ecout(Na,nbGrpGen,allField,nomGrpGen, file));
    }

    class ecout implements ActionListener 
    {   
        private int Na;
        private String [][] nomGrpGen ;
        private JTextField[][] allField;
        boolean correct=true;
        private int[] nbGrpGen;
        String chaine;
        File file;


        public ecout(int Na,int[] nbGrpGen, JTextField[][] allField, String[][] nomGrpGen, File file)
        {
            this.file = file;
            this.Na = Na;
            this.nbGrpGen =nbGrpGen;
            this.allField =allField;
            this.nomGrpGen =nomGrpGen;
        }

        public void actionPerformed(ActionEvent evt)
        {
            for(int i = 0;i < Na ;i++)
            {
                for(int j = 0;j < nbGrpGen[i] ;j++)
                {
                nomGrpGen[i][j] = allField[i][j].getText();
                    //chaine=allField[i][j].getText();
                    //nomGrpGen[i][j] ="A";
                  if(nomGrpGen[i][j]=="")
                  {
                      correct=false;
                  }
                }
            } 
            if(correct)
            {
                int i=0;
                int j=0;
                int nbElement;
                JOptionPane jop = new JOptionPane();
                String res;
                do
                {
                    res= jop.showInputDialog(null, "Veuillez indiquer le nombre d'attribut present au depart", "nombre d'attribut",JOptionPane.QUESTION_MESSAGE);
                }
                while(! isInteger(res));
                nbElement =Integer.parseInt(res); 


                int largeur=150+nbElement*30+80;
                int hauteur=30*(nbGrpGen[i])+100;
                if(largeur<600)
                {
                    largeur=600;
                }

                try 
                {
                    FileWriter fw = new FileWriter("test.txt");
                            BufferedWriter out = new BufferedWriter(fw);
                            out.write("aString");
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
                dispose();
                i=0;
                j=0;
                new Cadre_fenetreA3 ("initialisation du groupe"+nomGrpGen[i][j],5,5,largeur, hauteur, nbGrpGen[i], nbElement,nomGrpGen[i], i+1); 
            }
        }
    }
    public boolean isInteger( String input )  
    {  
       try  
       {  
          Integer.parseInt( input );  
          return true;  
       }  
       catch( Exception e)  
       {  
          return false;  
       }  
    }  

}
4

5 回答 5

12

这里,

try 
{
    FileWriter fw = new FileWriter("test.txt");
            BufferedWriter out = new BufferedWriter(fw);
            out.write("aString");
} 
catch (IOException e) 
{
    e.printStackTrace();
}

您将它包装在BufferedWriter一个默认缓冲区大小为 8KB 的文件中。所以只要你不写超过 8KB 并且不刷新/关闭它,那么它就不会出现在目标文件中。

完成后,您需要关闭编写器。这将刷新所有缓冲区并释放文件上的所有锁。正常的习惯用法是在与创建它finally的位置相同的try块中关闭它。这样您就可以保证在出现异常时也将其关闭,从而防止资源泄漏和永远锁定的文件。

Writer writer = null;

try {
    writer = new BufferedWriter(new FileWriter("test.txt"));
    writer.write("aString");
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}

或者,如果您已经使用 Java 7,那么您也可以使用新的try-with-resources 语句。当您离开try块时,它会自动关闭资源,从而减少样板代码。

try (Writer writer = new BufferedWriter(new FileWriter("test.txt"))) {
    writer.write("aString");
} catch (IOException e) {
    e.printStackTrace();
}

顺便说一句,我也会处理异常处理。而是向最终用户显示一些合理的错误消息,而不是将其简单地打印到标准输出并进一步忽略它。

于 2012-08-09T17:14:25.837 回答
3

关闭或刷新 writer:

FileWriter fw = new FileWriter("test.txt");
BufferedWriter out = new BufferedWriter(fw);
out.write("aString");
out.close();
于 2012-08-09T17:14:15.413 回答
2

你必须冲洗你的作家。

out.flush();
out.close();

在完成所有写入后放置这两行以关闭文件

于 2012-08-09T17:14:57.093 回答
2

按照这些序列成功写入文件....

File f = new File("d:\\test.txt");

FileWriter fw = new FileWriter(f);

BufferedWriter bw = new BufferedWriter(fw);

bw.write("Hello........");        // Writing to the file

bw.close();                       // Close the BufferedWriter

fw.close();                       // Close the FileWriter

关闭流很重要....

于 2012-08-09T17:25:16.213 回答
0
    import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class TestAndDelete {

    public static void main(String[] args) throws IOException {

        String test="hi how are you";
        File file =new File("D:/abcd/ravi.json");
        FileWriter fw=new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw=new BufferedWriter(fw);
        bw.append(test);
        bw.close();
        }
}
于 2013-05-28T18:04:46.567 回答