【问题标题】:Android download - using output stream approachAndroid下载——使用输出流方式
【发布时间】:2013-12-30 09:06:47
【问题描述】:
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return null;
        // return "Server returned HTTP " + connection.getResponseCode()
        // + " " + connection.getResponseMessage();

        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(IRConstant.issueFolder(y, m, d, i) + "/" + parms[0].currPage + ".zip");

        Log.d (TAG,"output: " + output);

        byte data[] = new byte[1024];
        int count;
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }

上面的代码是我如何实现下载功能的,问题是,如果输出流指定的文件已经存在,如何设置它覆盖现有文件?谢谢

【问题讨论】:

    标签: java android file-io io fileoutputstream


    【解决方案1】:

    在将数据写入文件之前检查其是否存在。如果文件存在删除它。以下代码仅对文件有效(不适用于目录)。

    File f = new File("path to file");
        if (f.exists()) {
           file.delete();
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用另一个构造函数:

      public FileOutputStream (File file, boolean append) 
      

      构造一个写入文件的新 FileOutputStream。如果 append 为 true 并且文件已经存在,它将被追加到;否则会被截断。如果文件不存在,将创建该文件。

      但我认为默认构造函数已经覆盖了现有文件

      public FileOutputStream (String path) 
      

      构造一个写入路径的新 FileOutputStream。如果文件存在,则文件将被截断,如果不存在则创建。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-26
        • 2020-04-10
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多