Pergunta

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

The above code is how I implement the download function, the problem is , how to set it to overwrite the existing file if there is a file aleready exist which specific by the output stream ? thanks

Foi útil?

Solução

Try to use another constructor:

public FileOutputStream (File file, boolean append) 

Constructs a new FileOutputStream that writes to file. If append is true and the file already exists, it will be appended to; otherwise it will be truncated. The file will be created if it does not exist.

But I think that the default constructor is already overwriting the existing file

public FileOutputStream (String path) 

Constructs a new FileOutputStream that writes to path. The file will be truncated if it exists, and created if it doesn't exist.

Outras dicas

Just before writing the data to the file check for its existence. If the file exists delete it. Below code is valid for files only (not for directories).

File f = new File("path to file");
    if (f.exists()) {
       file.delete();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top