2012-01-29 33 views
0

我正在运行一些不安全的代码,我已将其stdoutstderr流设置为FileStream s,并将其包装为PrintStream s。 (标准输出/必须重定向错误。)在PrintStream中写入的字节数限制

有什么办法来配置这些重定向FileStream S/PrintStream s到最多说10 MB的写入设定,因此,例如,

while (true) System.out.write("lots of bytes"); 

不会将过量的数据写入服务器的磁盘。

代码确实有15秒的时间限制,但我想在这里单独看守。

+0

只是不要子类'FileOutputStream'。 (你如何限制不安全代码的时间?) – 2012-02-04 21:22:54

+0

@ TomHawtin-tackline子类化FileOutputStream有什么问题? (我正在使用@弗拉德的解决方案,但...);而我只是使用BASH脚本。 – 2012-02-05 00:58:36

+0

有人可能会来,并添加一个额外的方法,让淘气的代码绕过你的覆盖。 (还要注意整数溢出。) – 2012-02-05 03:32:09

回答

2

一种方式做到这一点是定义你包中文件流,这使内部计数器,它增加每write,并达到设定的阈值后,开始投掷Exceptions或者干脆忽略写入FilterOutputStream

东西线沿线的:

import java.io.*; 
class LimitOutputStream extends FilterOutputStream{ 

    private long limit; 

    public LimitOutputStream(OutputStream out,long limit){ 
     super(out); 
     this.limit = limit; 
    } 

    public void write(byte[]b) throws IOException{ 
     long left = Math.min(b.length,limit); 
     if (left<=0) 
      return; 
     limit-=left; 
     out.write(b, 0, (int)left); 
    } 

    public void write(int b) throws IOException{ 
     if (limit<=0) 
      return; 
     limit--; 
     out.write(b); 
    } 

    public void write(byte[]b,int off, int len) throws IOException{ 
     long left = Math.min(len,limit); 
     if (left<=0) 
      return; 
     limit-=left; 
     out.write(b,off,(int)left); 
    } 
} 
+1

这里有一些线程问题。 – 2012-02-04 21:18:21

1

我有类似的任务,但阅读InputStreams从DB和做了一个小方法。 不想是显而易见的队长,但它也可以与inpustreams像FileInputStream太习惯:)


public static void writeBytes2File(InputStream is, String name,long limit) { 
    byte buf[] = new byte[8192]; 
    int len = 0; 
    long size = 0; 
    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(name); 
     while ((len = is.read(buf)) != -1) { 
      fos.write(buf, 0, len); 
      size += len; 
      if (size > limit*1024*1024) { 
       System.out.println("The file size exceeded " + size + " Bytes "); 
       break; 
      } 
     } 
     System.out.println("File written: " +name); 
    } 
catch (FileNotFoundException fnone) { 
    fnone.printStackTrace(); 
    } 
    catch (IOException ioe) { 
    ioe.printStackTrace(); 
    } 
    finally { 
     try { 
      if(is!=null){is.close();} 
      if (fos != null) {fos.flush();fos.close(); 
      }  
     } catch (Exception e) { 
    e.printStackTrace(); 
     } 
    }   
} 

希望有人可能会觉得它有用。