我想写一个Java代码,可以在Windows和Linux机器上使用,为Ethereum合约生成字节码。
我不熟悉shell脚本和linux,从我在互联网上读到的东西,我将能够通过bash执行以下批处理文件......但不幸的是,我得到了它不工作。我的代码是针对windows和linux的,并且为windows生成一个批处理文件,为linux生成一个shell文件,这到底是什么问题?
这段代码在linux下应该怎么用?在windows下,这段代码工作得很好。
String delim="";
String scriptName="";
String cmd="";
if (Linux) {
delim = "/";
scriptName="compile.sh";
cmd = "bash /c compile.sh";
}
else {
delim = "\\";
scriptName="compile.bat";
cmd = "cmd /c compile.bat";
}
String UUID = __SolidityFile.getValue(getContext(),"__UUID__");
String firstFolder = UUID.substring(0, 2);
String secondFolder = UUID.substring(2, 4);
String secondFolderLocation=com.mendix.core.Core.getConfiguration().getBasePath()+delim+"data"+delim+"files"+delim + firstFolder+ delim + secondFolder ;
String fileLocation=secondFolderLocation+ delim + UUID;
Core.getLogger("Solidity").info(fileLocation);
String solc =com.mendix.core.Core.getConfiguration().getResourcesPath()+delim+"node"+delim+"node_modules"+delim+"solc"+delim+"solcjs";
String node=com.mendix.core.Core.getConfiguration().getResourcesPath()+delim+"node.exe";
try {
// Block of code to try
final File file = new File(secondFolderLocation+delim+scriptName);
file.createNewFile();
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("cd "+secondFolderLocation);
writer.println(node+" "+ solc +" " +UUID +" --bin");
writer.println("exit");
writer.close();
Process p = Runtime.getRuntime().exec(cmd, null, new File(secondFolderLocation));
p.waitFor();
//file.delete();
String byteCodeFile = "";
String byteFileType = ByteCodeType.getCaption();
switch (byteFileType) {
case "TestToken":
byteCodeFile = fileLocation+"_TESTTOKEN.bin" ;
break;
case "SafeMath":
byteCodeFile = fileLocation+"_SafeMath.bin" ;
break;
case "Owned":
byteCodeFile = fileLocation+"_Owned.bin" ;
break;
case "ERC20Interface":
byteCodeFile = fileLocation+"_ERC20Interface.bin" ;
break;
case "ApproveAndCallFallBack":
byteCodeFile = fileLocation+"_ApproveAndCallFallBack.bin" ;
break;
}
Core.getLogger("Solidity").info(byteCodeFile);
Scanner scanner = new Scanner( new File(byteCodeFile), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close();
return text;
}
catch(Exception e) {
// Block of code to handle errors
return null ;
}
试着做吧。
当是Linux环境。
移除 bash /c
cmd = "/usr/local/bin/compile.sh";
你需要另一个环境条件(if)来运行下面的代码。
ProcessBuilder pb = new ProcessBuilder(cmd);
Process p = pb.start();
请你试一试,然后告诉我
我的代码
文件 optdevelopmentworkpacetestessrctestesMain.java
package testes;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String cmd = "/opt/development/workspace/testes/src/testes/script.sh";
ProcessBuilder pb = new ProcessBuilder(cmd);
Process p = pb.start();
System.out.println(p);
}
}
文件script.sh
mkdir stackoverfllow
文件夹已在 optdevelopmentworkspacetestes中创建。