Mercurial Hosting > luan
diff src/luan/lib/Utils.java @ 115:eacf6ce1b47d
add IoLib
git-svn-id: https://luan-java.googlecode.com/svn/trunk@116 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Thu, 29 May 2014 09:26:44 +0000 |
parents | 6ca02b188dba |
children | 1ff1c32417eb |
line wrap: on
line diff
--- a/src/luan/lib/Utils.java Mon May 26 05:39:54 2014 +0000 +++ b/src/luan/lib/Utils.java Thu May 29 09:26:44 2014 +0000 @@ -2,9 +2,17 @@ import java.io.File; import java.io.FileReader; +import java.io.FileWriter; import java.io.InputStreamReader; import java.io.Reader; +import java.io.Writer; import java.io.IOException; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URL; import luan.LuanState; import luan.LuanException; @@ -14,6 +22,8 @@ public final class Utils { private Utils() {} // never + private static final int bufSize = 8192; + public static void checkNotNull(LuanState luan,Object v,String expected) throws LuanException { if( v == null ) throw luan.JAVA.exception("bad argument #1 ("+expected+" expected, got nil)"); @@ -22,7 +32,7 @@ public static String readAll(Reader in) throws IOException { - char[] a = new char[8192]; + char[] a = new char[bufSize]; StringBuilder buf = new StringBuilder(); int n; while( (n=in.read(a)) != -1 ) { @@ -49,4 +59,59 @@ return s; } + public static void copyAll(InputStream in,OutputStream out) + throws IOException + { + byte[] a = new byte[bufSize]; + int n; + while( (n=in.read(a)) != -1 ) { + out.write(a,0,n); + } + } + + public static byte[] readAll(File file) + throws IOException + { + int len = (int)file.length(); + ByteArrayOutputStream out = new ByteArrayOutputStream(len) { + public byte[] toByteArray() { + return buf; + } + }; + FileInputStream in = new FileInputStream(file); + copyAll(in,out); + in.close(); + return out.toByteArray(); + } + + public static void write(File file,String s) + throws IOException + { + Writer out = new FileWriter(file); + out.write(s); + out.close(); + } + + public static void writeAll(byte[] a,OutputStream out) + throws IOException + { + copyAll(new ByteArrayInputStream(a),out); + } + + public static void writeAll(File file,byte[] a) + throws IOException + { + FileOutputStream fos = new FileOutputStream(file); + writeAll(a,fos); + fos.close(); + } + + public static byte[] readAll(InputStream in) + throws IOException + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + copyAll(in,out); + return out.toByteArray(); + } + }