如何使用java同时写入和读取文件?

时间:2013-12-26 12:38:43

标签: java

在我的程序中,我正在执行一个将输出写入文件的shell脚本。 我想逐行显示该文件内容。 这两项操作必须同时进行。

这是我的代码:

public static void myfun(String abc) throws IOException, InterruptedException {
    String customer = "xyz";
    nmapoutfile=runMT.instdir+"/var/nmapout."+customer;
    String nmapstatusfile = runMT.instdir+"/logs/nmapout."+customer+".log";
    String nmapdonefile = runMT.instdir+"/logs/nmapout."+customer+".done";

    String nmapcommand=runMT.instdir+"/bin/doscan.sh "+nmapoutfile+" "+IPRange+" "+nmapstatusfile+" "+nmapdonefile;

    System.out.println(nmapcommand);
    Runtime r = Runtime.getRuntime();
    Process pr = r.exec(nmapcommand);
    try {
        BufferedReader inbr = new BufferedReader (new FileReader(new File(nmapstatusfile)));        
    } 
    catch(Exception e){
         e.printStackTrace();
    }
    while (inbr.readLine()!=null){
        System.out.println("Line is .. " + inbr.readLine());
    }
    pr.waitFor();   
}

如何处理并发读写操作?

1 个答案:

答案 0 :(得分:0)

我建议您查看随机访问文件(请参阅http://docs.oracle.com/javase/tutorial/essential/io/rafs.html)。这个API使用起来有点复杂,因为你将读取字节而不是行,但它应该为你提供所需的东西。

如果您不想处理NIO,可以使用http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html代替。

相关问题