comparison src/luan/modules/Utils.java @ 167:4c0131c2b650

merge luan/lib into modules git-svn-id: https://luan-java.googlecode.com/svn/trunk@168 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Sun, 22 Jun 2014 04:28:32 +0000
parents src/luan/lib/Utils.java@d310ebf4d6e7
children
comparison
equal deleted inserted replaced
166:4eaee12f6c65 167:4c0131c2b650
1 package luan.modules;
2
3 import java.io.Reader;
4 import java.io.IOException;
5 import java.io.ByteArrayOutputStream;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.io.File;
9 import java.net.URL;
10 import java.net.MalformedURLException;
11 import luan.LuanState;
12 import luan.LuanException;
13
14
15 public final class Utils {
16 private Utils() {} // never
17
18 static final int bufSize = 8192;
19
20 public static void checkNotNull(LuanState luan,Object v,String expected) throws LuanException {
21 if( v == null )
22 throw luan.exception("bad argument #1 ("+expected+" expected, got nil)");
23 }
24
25 public static String readAll(Reader in)
26 throws IOException
27 {
28 char[] a = new char[bufSize];
29 StringBuilder buf = new StringBuilder();
30 int n;
31 while( (n=in.read(a)) != -1 ) {
32 buf.append(a,0,n);
33 }
34 return buf.toString();
35 }
36
37 public static void copyAll(InputStream in,OutputStream out)
38 throws IOException
39 {
40 byte[] a = new byte[bufSize];
41 int n;
42 while( (n=in.read(a)) != -1 ) {
43 out.write(a,0,n);
44 }
45 }
46
47 public static byte[] readAll(InputStream in)
48 throws IOException
49 {
50 ByteArrayOutputStream out = new ByteArrayOutputStream();
51 copyAll(in,out);
52 return out.toByteArray();
53 }
54
55 public static boolean exists(File file) {
56 try {
57 return file.exists() && file.getName().equals(file.getCanonicalFile().getName());
58 } catch(IOException e) {
59 throw new RuntimeException(e);
60 }
61 }
62
63 public static boolean isFile(String path) {
64 return exists(new File(path));
65 }
66
67 public static String toUrl(String path) {
68 if( path.indexOf(':') == -1 )
69 return null;
70 if( path.startsWith("java:") ) {
71 path = path.substring(5);
72 URL url = ClassLoader.getSystemResource(path);
73 return url==null ? null : url.toString();
74 }
75 try {
76 new URL(path);
77 return path;
78 } catch(MalformedURLException e) {}
79 return null;
80 }
81
82 public static boolean exists(String path) {
83 return isFile(path) || toUrl(path)!=null;
84 }
85 }