如何编写Java代码以将pwd(当前工作目录)保存到新文件。
在java中,在java代码中使用Perl脚本。
答案 0 :(得分:1)
您只能使用Java来完成。例如Paths class。
Path pwd = Paths.get("");
System.out.println(pwd.toAbsolutePath());
答案 1 :(得分:0)
您可以使用Runtime.getRuntime().exec()或Process API。 然后,您只需致电process.getInputStream()即可获得InputStream。
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Run {
public static void main(String[] args) throws IOException {
Process process = Runtime.getRuntime().exec("perl script.pl");
InputStream inputStream = process.getInputStream();
Scanner s = new Scanner(inputStream).useDelimiter("\\.");
String result = s.hasNext() ? s.next() : "";
System.out.println(result);
//Creating a text file to write the output of the executed command
//note that this will overwrite the file if it already exists
PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
writer.write(result);
writer.close();
// EDIT:
// writing commands to file name abc.txt
List<String> cmdList = new ArrayList<String>();
cmdList.add("echo '#!/bin/sh' >> ");
cmdList.add("echo 'pwd' >> ");
cmdList.add("echo 'output=$?' >>");
cmdList.add("echo 'exit $output' >>");
PrintWriter w = new PrintWriter("abc.txt");
for (String cmd : cmdList) {
w.println(cmd);
}
w.close();
}
}