在java中获取目录后如何将一些文件夹移回?
我使用了这段代码,它显示了我的项目目录在java中获取目录后如何将一些文件夹移回?,java,path,directory,Java,Path,Directory,我使用了这段代码,它显示了我的项目目录 System.out.println("Present Project Directory : "+ System.getProperty("user.dir")); 例如:C:\Users\Yousuf\Documents\NetBeansProjects\Store Management System 我要做的是移动到C:\Users\Yousuf\Documents,从通过此代码获得的目录中只返回两个文件夹。我该怎么办?这对我很有效,我得到了父目录
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));
例如:C:\Users\Yousuf\Documents\NetBeansProjects\Store Management System
我要做的是移动到C:\Users\Yousuf\Documents,从通过此代码获得的目录中只返回两个文件夹。我该怎么办?这对我很有效,我得到了父目录的父目录
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));
try
{
File file = new File(System.getProperty("user.dir")).getCanonicalFile();
System.out.println("Parent directory : " + file.getParent());
File file2 = new File(file.getParent()).getCanonicalFile();
System.out.println("Parent directory : " + file2.getParent());
} catch (Exception e)
{
System.out.println("error");
}
您可以使用相对路径.././向后导航2个文件夹。如果将其添加到路径的末尾,其有效位置将返回2个文件夹 之后,如果需要,可以使用normalize函数删除冗余元素,以返回实际路径2文件夹。但是,如果您只想导航到该文件夹,就没有必要对其进行规范化 只需将路径字符串放在原始路径字符串的位置即可
Path twoFoldersBack= Paths.get(originalPathString, "../../");
或者,如果要使路径正常化:
Path twoFoldersBack= Paths.get(originalPathString, "../../").normalize();
我的Jframe中有一个Jbutton,可以拍摄屏幕截图。现在我想将该图像保存在Windows中的文档或图片文件夹等文件夹中,我不想使用固定路径,因为其他电脑可能会有所不同。请使用String.split(“\”)并重建路径。。。但这只是一个变通办法,以防你没有更好的解决办法。是的,这就是我要问的。如何重建?这取决于程序运行的位置。在Windows上,它喜欢Linux或Mac上的
“C:”+“\\”+“用户”+…
,它喜欢“usr”+“/”+…
“路径文档=路径.get(System.getProperty(“user.dir”)).getParent().getParent()代码>。注意:这仅适用于当前配置。如果您从其他地方启动应用程序,则user.dir
是不同的。