我目前正在使用Java編程語言實現一個功能有限的shell。 shell的範圍也有限制的要求。我的任務是儘可能地模擬一個Unix shell。尋找以前的工作目錄來實現「cd - 」
當我執行cd命令選項時,我引用Basic Shell Commands page,它提到cd能夠返回到我使用命令「cd-」訪問的最後一個目錄。
由於我只給出了與方法public String execute(File presentWorkingDirectory, String stdin)
的接口。
我想知道是否有來自Java的API調用,我可以檢索以前的工作目錄,或者如果有此命令的任何實現?
我知道一個簡單的實現是聲明一個變量來存儲以前的工作目錄。不過,我目前擁有shell本身(帶有選項的命令),每次執行一個命令工具時,都會創建一個新線程。因此,我認爲「主」線程不宜存儲以前的工作目錄。
更新(6-Mar-'14):感謝您的建議!我現在已經與編碼器討論了shell,並添加了一個額外的變量來存儲以前的工作目錄。下面是共享的代碼示例:
public class CdTool extends ATool implements ICdTool {
private static String previousDirectory;
//Constructor
/**
* Create a new CdTool instance so that it represents an unexecuted cd command.
*
* @param arguments
* the argument that is to be passed in to execute the command
*/
public CdTool(final String[] arguments) {
super(arguments);
}
/**
* Executes the tool with arguments provided in the constructor
*
* @param workingDir
* the current working directory path
*
* @param stdin
* the additional input from the stdin
*
* @return the message to be shown on the shell, null if there is no error
* from the command
*/
@Override
public String execute(final File workingDir, final String stdin) {
setStatusCode(0);
String output = "";
final String newDirectory;
if(this.args[0] == "-" && previousDirectory != null){
newDirectory = previousDirectory;
}
else{
newDirectory = this.args[0];
}
if(!newDirectory.equals(workingDir) &&
changeDirectory(newDirectory) == null){
setStatusCode(DIRECTORY_ERROR_CODE);
output = DIRECTORY_ERROR_MSG;
}
else{
previousDirectory = workingDir.getAbsolutePath();
output = changeDirectory(newDirectory).getAbsolutePath();
}
return output;
}
}
P.S:請注意,這是不完整的執行代碼,這是不是光盤的全部功能。
如果您只想回到一個級別,請使用變量,如果您想返回更多級別,請維護一個堆棧。 – Kent