2014-02-18 101 views
0

所以我想在你里面使用cmd命令CD java程序返回java程序的源文件夹。现在我真的需要能够解析字符串并获取用户的用户名。这是我的意思。如果下面的代码生成:C:\ Users \ Bob \ Desktop \ newfolder \ JavaProgs \ prog1 ...我如何从字符串解析一个动态变量,如上面的用户名Bob?Java解析和更改CD

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; 
    } 
+0

这是高度依赖的部署。 –

+0

如果这是你想查找的用户名,有更好的方法。 UNIX以及Windows为此提供了环境变量。 – qqilihq

+0

@SotiriosDelimanolis你看,我试图复制的是安装程序的工作方式。我其实不知道如何,你能帮助我吗? – Arc

回答

0

我该如何解决:System.getProperty(“user.name”);

所以如果我想打印在当前登录用户的用户名,我会做:System.out.println(System.getProperty("user.name"));

:)