문제

        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

도움이 되었습니까?

해결책

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.

다른 팁

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top