在我的工具中,我让用户选择一个特定的文件。通过在该文件上调用getAbsolutePath()
,我将获得一个字符串,如
C:\文件夹\文件夹\文件夹\数据集\ MainFolder \文件夹\文件夹\文件夹\ myfile.xml中
如何将“MainFolder”的路径存储在新的String变量中。 我想从上面的例子中得到的是
C:\文件夹\文件夹\文件夹\数据集\ MainFolder \
结构总是
驱动器:\文件夹\随机\数\ \数据集\ main_folder_name \ folder1中\文件夹2 \ folder3 \ myfile.xml中
我正在查找的父文件夹始终具有名称“dataset”。该文件夹后面的那个是我感兴趣的那个。
答案 0 :(得分:1)
我强烈建议使用File API而不是String操作,这会使您远离正向与反斜杠的平台差异或任何其他差异。
代码
String path = "C:\\random\\number\\of\\folders\\dataset\\main_folder_name\\folder1\\folder2\\folder3\\myfile.xml";
File search = new File(path);
File lastParent = search;
while (search != null) {
if ("dataset".equals(search.getName())) {
break;
}
lastParent = search;
search = search.getParentFile();
}
if (lastParent != null) {
System.out.println(lastParent.getCanonicalPath());
}
输出
C:\random\number\of\folders\dataset\main_folder_name
答案 1 :(得分:1)
在程序中使用以下代码。这将解决您的期望:)
import java.util.StringTokenizer;
public class MainFolder {
public static void main(String args[]) {
String separator = "/";
StringTokenizer st = new StringTokenizer("C:/folder/folder/folder/dataset/MainFolder/folder/folder/folder/myfile.xml",separator);
String mainFolderPath = "";
String searchWord = "dataset";
while (st.hasMoreTokens()) {
mainFolderPath = mainFolderPath + st.nextToken() + separator;
if (mainFolderPath.contains(searchWord)) {
mainFolderPath = mainFolderPath + st.nextToken() + separator;
break;
}
}
System.out.println(mainFolderPath);
}
}
答案 2 :(得分:0)
URI
类具有相对性,并且文件为toURI。
String path = "C:\\folder\\folder\\folder\\dataset\\MainFolder\\folder\\folder\\folder\\myfile.xml";
String base = "C:\\folder\\folder\\folder\\dataset\\MainFolder";
File pathFile = new File(path);
File baseFile = new File(base);
URI pathURI = pathFile.toURI();
URI baseURI = baseFile.toURI();
URI relativeURI = baseURI.relativize(pathURI);
System.out.println(relativeURI.toString());
// folder/folder/folder/myfile.xml
File relativeFile = new File(relativeURI.getPath());
System.out.println(relativeFile.getPath());
// folder\folder\folder\myfile.xml
答案 3 :(得分:0)
可以通过仅使用String类的substring()和indexOf()方法来完成。代码是:
String path = "C:\\random\\number\\of\\folders\\dataset\\main_folder_name\\folder1\\folder2\\folder3\\myfile.xml";
int indexOfFirstBkSlashB4Dataset = path.indexOf("\\dataset");
String sub1 = path.substring(0,indexOfFirstBkSlashB4Dataset);
String sub2 = "\\dataset\\";
String sub3Intermediate = path.substring(indexOfFirstBkSlashB4Dataset+9,path.length());
int index2 = sub3Intermediate.indexOf("\\");
String sub4 = sub3Intermediate.substring(0,index2+1);
String output = sub1+sub2+sub4;
System.out.println(output);
输出为:C:\ random \ number \ of \ folders \ dataset \ main_folder_name \