2014-10-30 82 views
1

我怎样才能得到串的特定部分,让假设我有一个字符串特定部分

file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds 

,我想只得到

C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/ 

的字符串是动态的,所以它不是总是相同我只是想从开头和最后部分删除.ds扩展名的文件字

我试了一下

String resourceURI = configModel.eResource().getURI().toString(); 
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds 

String sourceFilePath = resourceURI.substring(6, resourceURI.length()-17) 
//This line gives C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/ 

This resourceURI.length() - 17可能会产生问题,因为SWA_Playground.ds并不总是相同的。 如何我刚刚从这个字符串中删除最后一个部分

感谢

+1

不知道我是否理解你,但如果你创建了一个File实例,你可以得到它的目录。那是你要的吗? – Korashen 2014-10-30 09:06:02

+0

您可能想检查http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FilenameUtils.html – 2014-10-30 09:08:02

回答

0

像这样:

String sourceFilePath = resourceURI.substring(
     resourceURI.indexOf("/") + 1, resourceURI.lastIndexOf('/') + 1); 

基本上,创建一个包含第一斜线和最后一个斜线之间的一切子。

输出将是:

C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/ 
0

你需要一个正则表达式:

resourceURI.replaceAll("^file:/", "").replaceAll("[^/]*$", "") 
2

您应该使用File class

String sourceFile = "file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds"; 
Sring filePath = sourceFile.substring(6); 

File f = new File(filePath); 
System.out.println(f.getParent()); 
System.out.println(f.getName()); 

首先你删除file:/前缀,那么你有一个Windows路径,你可以创建一个文件实例。

然后您使用getParent()方法获取文件夹路径,并使用getName()获取文件名。

0

你只是想第一个斜杠最后一个之前和之后,除去一切吗? 那么做到这一点:

String resourceURI = configModel.eResource().getURI().toString(); 
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds 

String[] sourceFilePathArray = ressourceURI.split("/"); 
String sourceFilePath = ""; 
for (int i = 1; i < sourceFilePathArray.length - 1; i++) 
    sourceFilePath = sourceFilePath + sourceFilePathArray[i] + "/"; 
//sourceFilePath now equals C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/ 
0

。利用lastIndexof从String类()方法。

String resourceURI = configModel.eResource().getURI().toString(); 
String sourceFilePath = resourceURI.substring(6, resourceURI.lastIndexOf('.'));