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.

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
  • 1
    Not possible. See bug at http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4045688 – Jayan Nov 16 '14 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. – Levon Nov 16 '14 at 16:22
  • 1
    The question you quoted 'http://stackoverflow.com/questions/840190' has all reasonable options listed. (ProcessBuilder, JNI/JNA...) – Jayan Nov 16 '14 at 16:24
  • Ok, thanks all .. I guess I'll delete this then. – Levon Nov 16 '14 at 16:42
  • unable to delete ... – Levon Nov 16 '14 at 21:06

1 Answers1

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.

Denis Borovikov
  • 737
  • 5
  • 9