简体   繁体   English

使用FileWriter覆盖Java中的文件

[英]overwriting a file in java using FileWriter

I have to accomplish a task of writing a set of data to file, use it, then overwrite it with new data. 我必须完成一项任务,将一组数据写入文件,使用它,然后用新数据覆盖它。 Thus overwrite of the file takes place repeatedly.I know i can accomplish the above by creating FileWriter object each time with the option to overwrite like below 因此,文件的覆盖会反复发生。我知道我可以通过每次创建FileWriter对象并使用如下所示的覆盖选项来完成上述操作

     FileWriter object = new FileWriter("fileName", false)

and close it to write to the file. 并将其关闭以写入文件。

If i am supposed to overwrite the file n number of times , according to the above method i need to create n number of FileWriter objects. 如果我应该覆盖文件n次,则根据上述方法,我需要创建n个FileWriter对象。 Is there any efficient way to overwrite a file repeatedly by only creating a single FileWriter object? 是否有任何有效的方法可以通过仅创建单个FileWriter对象来重复覆盖文件?

Not a direct answer, but anyway. 不是直接的答案,但是无论如何。

DON'T DO THAT! 不要那样做!

What do you think will happen if for some reason writing the new data to the file fails ? 如果由于某种原因将新数据写入文件失败,您会怎么办?

You not only lose your original file, but also the new file contents... 您不仅会丢失原始文件,还会丢失新文件的内容...

Write the new content to another file , ensure that it is well written and closed, and then rename the new file atomically to the original file. 将新内容写入另一个文件 ,确保其内容编写正确并已关闭, 然后将新文件自动重命名为原始文件。

PS: and do not forget to correctly .close() . PS:并且不要忘记正确使用.close()

PS2: if you use Java 7, use the new Files API. PS2:如果您使用Java 7,请使用新的Files API。

Its better to make a temp file and then rename the tempfile and delete the old like here: 最好先制作一个临时文件,然后重命名该临时文件并删除旧文件,如下所示:

    public static void nachtragenTRA(File files) throws IOException{

    Scanner sc=null;
        File f= files;
        String analyse = "";
        String NTausgabe = "";
        int max = 0;
        int k = 0;
        String updatedLine[] = new String [4];
        int filenr = 1;
        boolean sucess = false;

        try{
            sc= new Scanner(f);
        }catch(FileNotFoundException x){
            System.out.println("Error: File not found!");
        }
        while (sc.hasNextLine()){                                       //get next line

            analyse = sc.nextLine();

            max = analyse.length();                             //get line lenght

            StringBuffer sb = new StringBuffer(analyse);        //write analyse in StringBuffer 
                                                                //to change the string

            if(k == 1)
            {
                sb.replace(Daten.NTdatapos[3],max, Daten.NTProbentypTextfield.getText());
                updatedLine[0] =String.valueOf(sb);
            }
            else if(k == 2)
            {
                sb.replace(Daten.NTdatapos[4],max, Daten.NTPrueferTextfield.getText());
                updatedLine[1] =String.valueOf(sb);
            }
            else if(k == 3)
            {
                sb.replace(Daten.NTdatapos[5],max, Daten.NTKundeTextfield.getText());
                updatedLine[2] =String.valueOf(sb);
            }
            else if(k == 4)
            {
                sb.replace(Daten.NTdatapos[5],max, Daten.NTWerkstoffTextfield.getText());
                updatedLine[3] =String.valueOf(sb);
            }   

            if(k>3)
            {
                break;
            }

            k++;
        }
        sc.close();


        //NTausgabe=DatenTextarea.getText()+"\n"+updatedLine[0]+"\n"+updatedLine[1];
        //DatenTextarea.setText(String.valueOf(NTausgabe));

        //NTausgabe=DatenTextarea.getText()+"\n"+NTKundeTextfield.getText()+"\n"+NTPrueferTextfield.getText();
        //DatenTextarea.setText(String.valueOf(NTausgabe));


        //create tmp file with the new data
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(String.valueOf(f)+".tmp")));
        BufferedReader br = null;
        FileReader reader = null;

        try {
            reader = new FileReader(String.valueOf(f));
            br = new BufferedReader(reader);
            String line;

                while ((line = br.readLine()) != null)
                {
                    //Change speciffic lines
                    if(filenr == 2)
                    {
                        writer.println(updatedLine[0]);
                    }
                    else if(filenr == 3)
                    {
                        writer.println(updatedLine[1]);
                    }
                    else if(filenr == 4)
                    {
                        writer.println(updatedLine[2]);
                    }
                    else if(filenr == 5)
                    {
                        writer.println(updatedLine[3]);
                    }
                    //Andere Zeilen beibehalten
                    else
                    {   
                        writer.println(line);
                    }

                filenr = filenr + 1;
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                reader.close();
                br.close();

                File realName = new File(String.valueOf(f));
                realName.delete();                                              //delete old file
                writer.close();
                sucess = new File(String.valueOf(f)+".tmp").renameTo(realName); //rename tmp File to the others name
                if(sucess != true)
                {
                    NTausgabe=Daten.DatenTextarea.getText()+"\n"+"Rename File failed";
                    Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
                }
                else
                {
                    NTausgabe=Daten.DatenTextarea.getText()+"\n"+"File renamed sucessfully";
                    Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
                }
            }

 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM