基本上我想在Java中使用以下Scala代码。
command #> new java.io.File(outputFileName) !
或者相当于Python中的以下内容。
os.system(command + " > " + outputFileName)
我想出了以下代码。它够好吗?即使它,有没有更简单的方法呢?
String [] Command = new String[...];
Command[0] = ...
Command[1] = ...
...
Process proc = Runtime.getRuntime().exec(Command);
BufferedReader br = new BufferedReader(new InputStreamReader (proc.getInputStream()));
String line;
PrintWriter pw = new PrintWriter(outputFileName);
while ((line = br.readLine()) != null)
pw.write(line);
pw.close();
答案 0 :(得分:3)
我想出了以下代码。它够好吗?
这是一种主观评价。我们不在这里执行。
即使它,有没有更简单的方法呢?
使用ProcessBuilder
代替ProcessBuilder
会更加清晰。除其他事项外,String [] command = new String[] { "command", "-arg1", "-arg2" };
Process proc = new ProcessBuilder(command)
.redirectOutput(new File(outputFileName))
.start();
直接支持I / O重定向。您要做的事情可能如下所示:
import System.Environment
import System.IO
import Data.Maybe
import Text.Read
readStringList :: String -> Maybe [String]
readStringList = readMaybe
main = do --print "Enter file name"
handle <- openFile "1.txt" ReadMode
hSeek handle AbsoluteSeek 8
file <- hGetContents handle
let list = fromJust (readStringList file )
print list
let filterThis = "," :: String
let filtered = filter (/=filterThis) list
print filtered
除了更短更干净之外,它可能也更有效率,因为进程的输出将直接转到指定的文件,而不是必须读入Java然后写回。