Question

So I figured using the cmd command CD while inside you java program returns the java program's source folder. Now what I exactly need to be able to parse the String and grab the username of the user. Here's what I mean.

If the code below, which works, produces : C:\Users\Bob\Desktop\newfolder\JavaProgs\prog1 ... how can I parse a dynamic variable, like the username Bob above, from a String?

public static void cdir() throws IllegalCommandException {
        try{
            String command = "cd";
            String s = get_commandline_results(command);
            String[] temp1 = s.split("\n");
            LinkedList<String> temp2 = new LinkedList<String>(Arrays.asList(temp1));
            System.out.println(temp2.get(0));
            filePath = temp2.get(0);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public static String get_commandline_results(String cmd)
        throws IOException, InterruptedException, IllegalCommandException{

        if (!authorizedCommand(cmd)) {
            throw new IllegalCommandException();
        }
        String result = "";
        final Process p = Runtime.getRuntime().exec(String.format("cmd /c %s", cmd));
        final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
        final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
        stderr.start();
        stdout.start();
        final int exitValue = p.waitFor();
        if (exitValue == 0){
            result = stdout.toString();
        }
        else{
            result = stderr.toString();
        }
        return result;
    }
    public static boolean authorizedCommand(String cmd){
        if (cmd.equals("cd"))
            return true;
        return false;
    }
Was it helpful?

Solution

How I solved : System.getProperty("user.name");

So If I want to print the username of the currently logged in user I would do : System.out.println(System.getProperty("user.name"));

:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top