简体   繁体   English

Java I / O延迟在文件系统中创建文件

[英]Java I/O delay creating a file in the file system

I have legacy code which uses BufferedWriter to create a file in the file system. 我有使用BufferedWriter在文件系统中创建文件的旧版代码。

The problem is that when there is some verification error in program it creates an empty file. 问题是,当程序中出现某些验证错误时,它将创建一个空文件。 It should not create the file at all when there is an verification error, but the error is detected only when data is written to it (verification). 发生验证错误时,它根本不应该创建文件,但是仅当将数据写入到文件中(验证)时,才会检测到该错误。 PFB the example code: PFB示例代码:

//Legacy code
    File file1= new File(<path to directory>);
    BufferedWriter dBufferedWriter = new BufferedWriter(new FileWriter(file1));

//Code that can have error and this repeats in loop
    String str = "some string or null if error occurs";
    if(validate(str)){  
        dBufferedWriter.write(str);
    }

//Later at end
    dBufferedWriter.close();

Is there a way to delay creating a file when it's not needed? 有没有必要在不需要文件时延迟创建文件的方法?

When you create new FileWriter it creates new file if this file does not exists. 创建新的FileWriter ,如果该文件不存在,它将创建新文件。 If you don't need any file in case of exception, you can use try{...}finally{...} : 如果在异常情况下不需要任何文件,则可以使用try{...}finally{...}

File file = new File(<path to directory>);
BufferedWriter dBufferedWriter = new BufferedWriter(new FileWriter(file));
try{        
    // some code where you can get exception

    String str = "some string or null if error occurs";
    dBufferedWriter.write(str);     
}finally{
    dBufferedWriter.close();
    if(file.length()==0) file.delete();
}

By the way, it is a good practice to use finally for close resource, even if you don't need to check file length. 顺便说一句,即使您不需要检查文件长度,最好还是使用finally作为关闭资源。

Sure, if you can change legacy code's order, make it so, that the file will be created after verification code. 当然,如果您可以更改旧代码的顺序,请按顺序进行操作,以便在验证代码之后创建文件。 In case of exception code after verification loop will not be reached: 如果没有验证循环后的异常代码:

// some code where you can get exception

Writer fileWriter = new FileWriter(new File(<path to directory>));
String str = "some string or null if error occurs";
dBufferedWriter.write(str);     
dBufferedWriter.close();

So the legacy code shouldn't create the file if it isn't going to be needed. 因此,如果不需要旧文件,则不应创建该文件。 So fix that. 所以解决这个问题。

String str = "some string or null if error occurs";
if(validate(str)){  
    File file1= new File(<path to directory>);
    BufferedWriter writer1 = new BufferedWriter(new FileWriter(file1));
    dBufferedWriter.write(str);
    dBufferedWriter.close();        
}

... assuming dBufferedWriter and writer1 are the same thing. ...假设dBufferedWriterwriter1是同一件事。

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

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