【问题标题】:How to write and read from file simultaneously using java? [duplicate]如何使用java同时写入和读取文件? [复制]
【发布时间】:2013-12-26 12:38:43
【问题描述】:

在我的程序中,我正在执行一个将输出写入文件的 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();   
}

如何处理并发读写操作??

【问题讨论】:

  • 你到底为什么要这么做?这几乎就像将您的应用程序编程为强制交换一样。
  • 如果你在linux上,你可以tail文件..
  • @Martijn Courteaux - 我正在编写不同网络命令的输出。我想显示这些命令的结果并想相应地执行操作
  • 您正在重新实现标准命令tee。您为什么不研究一下使用该命令,以免自己头疼。

标签: java


【解决方案1】:

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

如果您不想与 NIO 打交道,可以改用http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多