Este tópico descreve como verificar se um objeto específico existe.
Notas de uso
Neste tópico, é usado o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints compatíveis, consulte Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações, consulte 配置访问凭证.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Client configuration.
Você deve ter a permissão
oss:GetObjectpara verificar se um objeto existe. Para obter mais informações, consulte Grant a custom policy.
Exemplos
O código a seguir mostra como verificar se o objeto exampleobject.txt existe no bucket examplebucket.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// The endpoint of the China (Hangzhou) region is used in this example. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
String objectName = "exampleobject.txt";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Check whether the object exists. If the return value is true, the object exists. Otherwise, the bucket or object does not exist.
// Specify whether to perform redirection or mirroring-based back-to-origin. The default value is true, which indicates that 302 redirection and mirroring-based back-to-origin are ignored. If you set isINoss to false, 302 redirection or mirroring-based back-to-origin is performed.
//boolean isINoss = true;
boolean found = ossClient.doesObjectExist(bucketName, objectName);
//boolean found = ossClient.doesObjectExist(bucketName, objectName, isINoss);
System.out.println(found);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Referências
Para acessar o código de exemplo completo, consulte o exemplo no GitHub.