development

Java에서 현재 작업 디렉토리를 변경 하시겠습니까?

big-blog 2020. 6. 1. 08:21
반응형

Java에서 현재 작업 디렉토리를 변경 하시겠습니까?


Java 프로그램 내에서 현재 작업 디렉토리를 어떻게 변경합니까? 내가 당신이 단순히 할 수 없다는 문제 주장에 대해 찾을 수 있었던 모든 것이지만, 나는 그것이 실제로 사실이라고 믿을 수 없습니다.

일반적으로 시작되는 디렉토리에서 하드 코딩 된 상대 파일 경로를 사용하여 파일을 여는 코드 조각이 있으며 내부에서 시작할 필요없이 다른 Java 프로그램에서 해당 코드를 사용할 수 있기를 원합니다. 특정 디렉토리. 그것은 당신이 전화 할 수 있어야하는 것처럼 보이지만 System.setProperty( "user.dir", "/path/to/dir" ), 내가 알아낼 수있는 한 그 줄을 전화하는 것은 조용히 실패하고 아무것도하지 않습니다.

Java가 현재 작업 디렉토리 거나 상대 파일 경로를 사용하여 파일을 열 수 없다는 사실이 아니라면 Java 가이 작업을 수행 할 수 없었는지 이해 합니다 ....


순수한 Java에서는이를 수행 할 수있는 확실한 방법이 없습니다. 설정 user.dir을 통해 속성을 System.setProperty()또는 java -Duser.dir=...후속 작품에 영향을 미치는 것으로 보인다 Files아니라 예 FileOutputStreams.

File(String parent, String child)당신이 쉽게 스와핑을 허용, 파일 경로에서 별도로 디렉토리 경로를 구축하는 경우 생성자는 도움이 될 수 있습니다.

대안은 다른 디렉토리에서 Java를 실행하도록 스크립트를 설정하거나 아래 제안 된대로 JNI 기본 코드 사용하는 것 입니다.

관련 Sun 버그 는 2008 년 "수정되지 않음"으로 종료되었습니다.


ProcessBuilder로 레거시 프로그램을 실행 하면 작업 디렉토리 를 지정할 수 있습니다 .


시스템 프로퍼티 "으로 user.dir"을 사용하여이 작업을 수행 할 수있는 방법은. 이해해야 할 중요한 부분은 getAbsoluteFile ()을 호출해야하거나 (아래에 표시된대로) 그렇지 않으면 상대 경로가 기본 "user.dir"값 에 대해 분석됩니다 .

import java.io.*;

public class FileUtils
{
    public static boolean setCurrentDirectory(String directory_name)
    {
        boolean result = false;  // Boolean indicating whether directory was set
        File    directory;       // Desired current working directory

        directory = new File(directory_name).getAbsoluteFile();
        if (directory.exists() || directory.mkdirs())
        {
            result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
        }

        return result;
    }

    public static PrintWriter openOutputFile(String file_name)
    {
        PrintWriter output = null;  // File to open for writing

        try
        {
            output = new PrintWriter(new File(file_name).getAbsoluteFile());
        }
        catch (Exception exception) {}

        return output;
    }

    public static void main(String[] args) throws Exception
    {
        FileUtils.openOutputFile("DefaultDirectoryFile.txt");
        FileUtils.setCurrentDirectory("NewCurrentDirectory");
        FileUtils.openOutputFile("CurrentDirectoryFile.txt");
    }
}

JNA / JNI를 사용하여 libc를 호출하여 PWD를 변경할 수 있습니다. JRuby를들는 POSIX를 만들기위한 편리한 자바 라이브러리가 전화 통화를 JNA-POSIX 여기입니다 받는다는 정보

여기 에서 그 사용 예를 볼 수 있습니다 (Clojure 코드, 죄송합니다). chdirToRoot 함수를보십시오


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...


As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.

See Runtime.exec javadocs

Specifically,

public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException

where dir is the working directory to run the subprocess in


The working directory is a operating system feature (set when the process starts). Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:

File f = new File ( System.getProperty("someprop"), myFilename)

The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.

Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.


I have tried to invoke

String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());

It seems to work. But

File myFile = new File("localpath.ext"); InputStream openit = new FileInputStream(myFile);

throws a FileNotFoundException though

myFile.getAbsolutePath()

shows the correct path. I have read this. I think the problem is:

  • Java knows the current directory with the new setting.
  • But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.

The solution may be:

File myFile = new File(System.getPropety("user.dir"), "localpath.ext");

It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.

~~~~JcHartmut


You can use

new File("relative/path").getAbsoluteFile()

after

System.setProperty("user.dir", "/some/directory")

System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());

Will print

C:\OtherProject\data\data.csv

이 질문에 대한 다른 가능한 대답은 파일을 여는 이유에 따라 달라질 수 있습니다. 이 파일은 특성 파일입니까, 아니면 응용 프로그램과 관련된 구성이있는 파일입니까?

이 경우 클래스 경로 로더를 통해 파일을로드하려고하면 Java가 액세스 할 수있는 모든 파일을로드 할 수 있습니다.


쉘에서 명령을 실행하면 "java -cp"와 같은 것을 작성하고 ":"로 구분하여 원하는 디렉토리를 추가 할 수 있습니다. java가 한 디렉토리에서 무언가를 찾지 못하면 다른 디렉토리에서 찾으십시오. 내가하는 일입니다.


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);

참고 URL : https://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java

반응형