programing

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

nicescript 2022. 7. 14. 21:49
반응형

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

Java 프로그램 내에서 현재 작업 디렉토리를 변경하려면 어떻게 해야 합니까?제가 이 문제에 대해 발견한 모든 것은 단순히 당신이 그것을 할 수 없다는 것이지만, 저는 그것이 사실이라는 것을 믿을 수 없습니다.

통상적으로 시작되는 디렉토리에서 하드 코드화된 상대 파일 경로를 사용하여 파일을 여는 코드 조각이 있는데, 특정 디렉토리 내에서 시작하지 않고 다른 Java 프로그램 내에서 해당 코드를 사용할 수 있기를 원합니다. 될 것 요.System.setProperty( "user.dir", "/path/to/dir" )하지만 제가 알 수 있는 한, 그 회선을 호출하는 것은 묵묵히 실패하고 아무 것도 하지 않습니다.

Java가 이를 허용하지 않았다면 현재 작업 디렉토리를 가져올 수 있었을 뿐만 아니라 상대 파일 경로를 사용하여 파일을 열 수 있었을지도 모릅니다.

【Java】【Java】【Java】【Java】【Java】【Java】【Java】【Java】【Java】【Java】키로 했다.의 설정user.dir를 통한 System.setProperty() ★★★★★★★★★★★★★★★★★」java -Duser.dir=...의 을 미치는 것 .Files 예를 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, FileOutputStreams.

파일 경로와 별도로 디렉토리 경로를 구축하면 생성자가 도움을 줄 수 있으므로 쉽게 스왑할 수 있습니다.

다른 방법으로 다른 디렉토리에서 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/J를 사용하여 PWD를 변경할 수 있습니다.Libc에 콜을 발신하는 NI.JRuby는 jnr-posix라고 불리는 POSIX 호출을 할 수 있는 편리한 Java 라이브러리를 가지고 있습니다.여기 maven 정보가 있습니다.

전술한 바와 같이 JVM의 CWD는 변경할 수 없지만 Runtime.exec()을 사용하여 다른 프로세스를 시작할 경우 작업 디렉토리를 지정할 수 있는 오버로드된 메서드를 사용할 수 있습니다.이는 Java 프로그램을 다른 디렉토리에서 실행하기 위한 것이 아니라 Perl 스크립트 등의 다른 프로그램을 실행해야 할 경우 JVM의 작업 디렉토리를 변경하지 않고 해당 스크립트의 작업 디렉토리를 지정할 수 있습니다.

런타임」을 참조해 주세요.exec javadocs

구체적으로는

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

서 ''는dir입니다.

제가 제대로 이해했다면 자바 프로그램은 현재 환경변수의 복사본으로 시작됩니다.변경 사항:System.setProperty(String, String)는 원래 환경 변수가 아닌 복사본을 수정합니다.이게 쑨양이 왜 이런 행동을 선택했는지에 대한 완벽한 이유를 제공하는 건 아니지만, 아마 조금 더 밝혀줄지도...

작업 디렉토리는 운영 체제 기능(프로세스 시작 시 설정)입니다. 속성System Property(시스템 시스템」)-Dsomeprop=/my/path파일 부모로서 코드로 사용합니다.

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

스마트하고 할 수 은, 디렉토리에 로 파일을 것이 , 하는 것 입니다(</ CHANGE:></FONT CHANGE:></FONT CHANGE:></FONT CHANGE:></FONT CHANGE:></FONT CHANGE:></FONT CHANGE:></ CHANGE:></FONT CHANGE:></FONT CHANGE:></FONT CHANGE:new File("blah.txt")파일 경로를 직접 구축하기만 하면 됩니다.

가 기본 후 로 .user.dir작동 방식을 그러나 환경변수 작동 방식을 변경하는 것보다 프로그램의 논리를 개선하는 것이 훨씬 쉽습니다.

호출을 시도했습니다.

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

효과가 있는 것 같아요.그렇지만

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

FileNotFoundException그래도

myFile.getAbsolutePath()

에 올바른 경로를 나타냅니다.나는 이것을 읽은 적이 있다.문제는 다음과 같습니다.

  • Java는 새 설정으로 현재 디렉토리를 인식합니다.
  • 그러나 파일 처리는 운영 체제에서 수행합니다.유감스럽게도 새로운 set current directory는 인식되지 않습니다.

해결책은 다음과 같습니다.

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

JVM에 의해 알려진 현재 디렉토리와 함께 파일 Object를 absolute로 만듭니다.그러나 이 코드는 중고 클래스에 존재해야 하며 재사용 코드를 변경해야 합니다.

~~~~JcHartmut

사용할 수 있습니다.

새 파일("relative/path").getAbsoluteFile()

끝나고

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

인쇄하다

C:\OtherProject\data\data.csv

JNI 또는 JNA를 사용하여 프로세스의 실제 작업 디렉토리를 변경할 수 있습니다.

JNI에서는 네이티브 함수를 사용하여 디렉토리를 설정할 수 있습니다.POSIX 방식은chdir() 를 사용할 수 SetCurrentDirectory()

JNA를 사용하면 기본 기능을 Java 바인더로 래핑할 수 있습니다.

Windows 의 경우:

private static interface MyKernel32 extends Library {
    public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);

    /** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
    int SetCurrentDirectoryW(char[] pathName);
}

POSIX 시스템의 경우:

private interface MyCLibrary extends Library {
    MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);

    /** int chdir(const char *path); */
    int chdir( String path );
}

이 질문에 대한 다른 가능한 답변은 파일을 여는 이유에 따라 달라질 수 있습니다.속성 파일입니까, 아니면 애플리케이션과 관련된 설정이 있는 파일입니까?

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

셸에서 명령어를 실행하면 "java -cp"와 같은 것을 쓰고 ":"로 구분하고 싶은 디렉토리를 추가할 수 있습니다.Java는 한 디렉토리에서 무언가를 찾지 못하면 다른 디렉토리에서 검색하려고 시도합니다.이것이 제가 하는 일입니다.

File System View 사용

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

반응형