java Java读取文件,如果它不存在则创建它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5464631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:14:28  来源:igfitidea点击:

Java read a file, if it doesn't exist create it

javafiletext

提问by Franky

here's my code

这是我的代码

public String path;
public String fileName;
public static void readData() throws IOException{
    try {
        path="myPath"
        fileName="myFileName";
        fstream = new FileInputStream(path+fileName);
        br = new BufferedReader(new InputStreamReader(fstream));
        //do something...//
        }
        br.close();
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Reading file error");
        Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I wanted to know how to check if the fstream exists. If it doesn't exist, a new file has to be created. How can I do this? Thanks

我想知道如何检查 fstream 是否存在。如果它不存在,则必须创建一个新文件。我怎样才能做到这一点?谢谢

回答by Jesse

Here's a possible solution:

这是一个可能的解决方案:

public static void readData() throws IOException
{
    File file = new File(path, filename);

    if (!file.isFile() && !file.createNewFile())
    {
        throw new IOException("Error creating new file: " + file.getAbsolutePath());
    }

    BufferedReader r = new BufferedReader(new FileReader(file));

    try 
    {
        // read data
    }finally
    {
        r.close();
    }
}

回答by DES

Something's missing in your code - there's a closing brace with no corresponding opening brace.

您的代码中缺少某些内容 - 有一个没有相应的左大括号的右大括号。

But to answer your question, create a Fileobject first and use exists(), then createNewFile()if exists()returns false. Pass the Fileobject instead of the filename to the FileInputStreamconstructor.

但是要回答您的问题,File请先创建一个对象并使用exists(),然后createNewFile()ifexists()返回false。将File对象而不是文件名传递给FileInputStream构造函数。

BTW, it would have taken you less time to google the answer than it did to type in your question here.

顺便说一句,与在此处输入问题相比,用谷歌搜索答案所花的时间会更少。

回答by Greg

To check if the file filenameexists in path, you can use new File(path, filename).exists().

要检查文件是否filename存在于 中path,您可以使用new File(path, filename).exists().

The exists methodreturns true if a file or directory exists on the filesystem for the specified File.

存在的方法,如果一个文件或目录在文件系统中指定的存在,返回true File

To verify that the file is a file and not a directory, you can use the isFile method.

要验证文件是文件而不是目录,您可以使用isFile 方法

See the javadoc for java.io.Filefor more information.

有关更多信息,请参阅java.io.Filejavadoc

回答by Jean-Christophe Fortin

if(new File("filename").exists())
   ...

it should do what you want.

它应该做你想做的。

回答by pajton

You are already catching FileNotFoundExceptionand this is the very place where you know that the file you wanted to read doesn't exist and you can create it.

您已经FileNotFoundException知道了,这正是您知道要读取的文件不存在的地方,您可以创建它。