【问题标题】:Java read a file, if it doesn't exist create itJava读取一个文件,如果它不存在则创建它
【发布时间】:2011-03-28 20:20:54
【问题描述】:

这是我的代码

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);
    }
}

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

【问题讨论】:

    标签: java file text


    【解决方案1】:

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

    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();
        }
    }
    

    【讨论】:

    • 您可能还想查看使用InputStreamReader,指定Charset,而不是使用默认字符集的FileReader...
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      如果文件系统上存在指定File 的文件或目录,exists method 返回 true。

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

      请参阅javadoc for java.io.File 了解更多信息。

      【讨论】:

      • 或者更好的new File(path,filename).exists(),它将自动为您所在的操作系统插入正确的路径分隔符。
      【解决方案4】:
      if(new File("filename").exists())
         ...
      

      它应该做你想做的。

      【讨论】:

        【解决方案5】:

        您已经捕捉到FileNotFoundException,而这正是您知道要读取的文件不存在并且您可以创建它的地方。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-20
          • 2014-11-09
          • 1970-01-01
          • 2020-07-12
          • 2021-01-31
          • 2022-12-09
          • 2019-08-09
          • 2016-03-17
          相关资源
          最近更新 更多