Changing the current working directory in Java?

前端 未结 14 1501
太阳男子
太阳男子 2020-11-22 05:32

How can I change the current working directory from within a Java program? Everything I\'ve been able to find about the issue claims that you simply can\'t do it, but I can\

相关标签:
14条回答
  • 2020-11-22 05:57

    If I understand correctly, a Java program starts with a copy of the current environment variables. Any changes via System.setProperty(String, String) are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...

    0 讨论(0)
  • 2020-11-22 05:59

    Use FileSystemView

    private FileSystemView fileSystemView;
    fileSystemView = FileSystemView.getFileSystemView();
    currentDirectory = new File(".");
    //listing currentDirectory
    File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
    fileList = new ArrayList<File>();
    dirList = new ArrayList<File>();
    for (File file : filesAndDirs) {
    if (file.isDirectory())
        dirList.add(file);
    else
        fileList.add(file);
    }
    Collections.sort(dirList);
    if (!fileSystemView.isFileSystemRoot(currentDirectory))
        dirList.add(0, new File(".."));
    Collections.sort(fileList);
    //change
    currentDirectory = fileSystemView.getParentDirectory(currentDirectory);
    
    0 讨论(0)
提交回复
热议问题