您的位置:首页 > 编程语言 > Java开发

Azure File服务(5): Java开发

2016-05-12 18:41 537 查看

使用Java管理Azure文件共享服务

Azure文件共享服务提供了多种方式的访问接口,包括Powershell,.Net, Java, Python等等,本章主要介绍如何使用Java来访问Azure File存储。 Java基本开发环境的搭建,Eclipse的插件安装,IntelliJ IDEA的插件安装,请参考我的文档:

http://cloudapps.blog.51cto.com/3136598/1772092关于访问连接串,SDK默认的连接串是指向global Azure的,即"*.core.windows.net",但中国区的Azure的访问的服务URL是".core.chinacloudapi.cn",所以需要在链接字符串中指定EndpointSuffix。

关于存储的访问协议,默认情况下是https协议,但你也可以指定为http协议,一般建议在Azure内部访问存储的时候使用http,而在外部访问的时候使用https进行加密传输。
public static final String storageConnectionString = "DefaultEndpointsProtocol=http;" + "AccountName=mystorageacctfile;" + "AccountKey=YOURStorageAccountKey;" + "EndpointSuffix=core.chinacloudapi.cn"; 如果需要进行加密传输,修改DefaultEndpointsProtocol=https.
Fileshare的名字命名是有要求的,例如必须全部小写等,否则在Java里面你会看到如下错误:



具体命名规则请参考:https://msdn.microsoft.com/library/azure/dn167011.aspx首先需要初始化存储上下文,得到文件访问句柄:
storageAccount = CloudStorageAccount.parse(storageConnectionString); System.out.println(storageAccount.getBlobEndpoint()); CloudFileClient fileClient = storageAccount.createCloudFileClient();
创建一个新的文件共享:
CloudFileShare share = fileClient.getShareReference(myFileShare); if (share.createIfNotExists()){System.out.println("New file share:" + myFileShare +"created!");}
文件共享创建完成后,我们在该文件共享下建立一个目录:
//Get a reference to the root directory for the share.CloudFileDirectory rootDir = share.getRootDirectoryReference(); //Get a reference to the sampledir directoryCloudFileDirectory sampleDir = rootDir.getDirectoryReference(mydirectory); if (sampleDir.createIfNotExists()){System.out.println("sampledir created");}else {System.out.println("sampledir already exists");
}上传或者下载一个文件共享中的文件,下载文件可以将他通过Outstream写入到本地文件等多种方式,本示例中直接打印出来:
//upload a test file to the sampledirCloudFile cloudFile = sampleDir.getFileReference("hdinsight.publishsettings"); if(!cloudFile.exists()){ cloudFile.uploadFromFile(testfilePath);}else{ //Download file if exists System.out.println(cloudFile.downloadText());}
以下例子展示了如何删除一个文件,删除一个目录,请注意在删除目录的时候,该目录下必须没有任何文件,否则会报错:
CloudFile cloudFile = sampleDir.getFileReference(testFilename);
//Delete specified file if ( cloudFile.deleteIfExists() ){ System.out.println(testFilename + " was deleted!"); } //Get a reference to the root directory for the share.CloudFileDirectory rootDir = share.getRootDirectoryReference(); //Get a reference to the sampledir directoryCloudFileDirectory sampleDir = rootDir.getDirectoryReference(mydirectory);// Delete the directoryif ( sampleDir.deleteIfExists() ){ System.out.println("Directory "+ sampleDir +" was deleted!");} 10.关于在你调用Azure file接口的时候,使用https链接,即将链接字符串中的DefaultEndpointsProtocol设置为https,你可能会碰到如下错误:

即使你使用的是最新的Azure China 的WoSign的证书,也会出现上述问题,具体原因和Azure China没有关系,你懂的:)解决办法请参考我的博文: http://cloudapps.blog.51cto.com/3136598/1744342
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Azure Java File