0

Using the various Java APIs I can implement the following shell commands in Java successfully: pwd, dir/ls, copy/cp, del/rm without invoking the shell itself to execute these command to for me.

E.g.,

    case "pwd":
        System.out.println(System.getProperty("user.dir"));
        break;

    case "dir":
    case "ls":
        File myDir = new File(System.getProperty("user.dir"));
        String[] filesInDir = myDir.list();
        for(String fn: filesInDir)
            System.out.println(fn);
        break;

The only basic command that is giving me trouble is "cd". Surely there must be an API function that would let me do this? However if there is I've missed it.

Note: I am not trying to execute anything external to the program, I simply want to be able to navigate the file system interactively for the duration of the program run and manipulate files in a very limited way via the API. In other words, this program emulates a very basic shell.

I've seen these question, but they haven't really helped, one states this is not possible, true?

How to change current directory in JAVA?

Changing the current working directory in Java?

Changing the current directory in Java to implement "cd" command in linux

Using Windows 7 with JDK 7.

5
  • 1
    Not possible. See bug at bugs.java.com/bugdatabase/view_bug.do?bug_id=4045688 Commented Nov 16, 2014 at 16:13
  • @Jayan Wow (and interesting) .. it seems like such a basic file system operation for it not to be implemented - thanks for the link. I wonder if there's another workaround for this. Commented Nov 16, 2014 at 16:22
  • 1
    The question you quoted 'stackoverflow.com/questions/840190' has all reasonable options listed. (ProcessBuilder, JNI/JNA...) Commented Nov 16, 2014 at 16:24
  • Ok, thanks all .. I guess I'll delete this then. Commented Nov 16, 2014 at 16:42
  • unable to delete ... Commented Nov 16, 2014 at 21:06

1 Answer 1

1

There is no such api function but you can emulate it: store current directory in variable. During initialization assign this variable to System.getProperty("user.dir"). In all your methods use this variable. "cd" command should change this variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.