View Javadoc

1   /*
2   	Copyright (c) 2009 Olivier Chafik, All Rights Reserved
3   	
4   	This file is part of JNAerator (http://jnaerator.googlecode.com/).
5   	
6   	JNAerator is free software: you can redistribute it and/or modify
7   	it under the terms of the GNU General Public License as published by
8   	the Free Software Foundation, either version 3 of the License, or
9   	(at your option) any later version.
10  	
11  	JNAerator is distributed in the hope that it will be useful,
12  	but WITHOUT ANY WARRANTY; without even the implied warranty of
13  	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  	GNU General Public License for more details.
15  	
16  	You should have received a copy of the GNU General Public License
17  	along with JNAerator.  If not, see <http://www.gnu.org/licenses/>.
18  */
19  package com.ochafik.io;
20  import java.io.BufferedInputStream;
21  import java.io.BufferedOutputStream;
22  import java.io.BufferedReader;
23  import java.io.ByteArrayOutputStream;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileOutputStream;
27  import java.io.FileReader;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.InputStreamReader;
31  import java.io.OutputStream;
32  import java.io.Reader;
33  import java.io.UnsupportedEncodingException;
34  import java.net.HttpURLConnection;
35  import java.net.URL;
36  import java.net.URLConnection;
37  import java.util.ArrayList;
38  import java.util.List;
39  import java.util.Properties;
40  import java.util.regex.Pattern;
41  
42  //import javax.net.ssl.HostnameVerifier;
43  //import javax.net.ssl.HttpsURLConnection;
44  //import javax.net.ssl.SSLSession;
45  
46  import com.ochafik.util.string.RegexUtils;
47  public class ReadText { 
48  	public static final String readText(Reader in) throws IOException {
49  		int len;
50  		char ch[]=new char[1024];
51  		StringBuffer b=new StringBuffer();
52  		while ((len=in.read(ch))>0) b.append(ch,0,len);
53  		return b.toString();
54  	}
55  	public static final String readText(File f) {
56  		if (f == null)
57  			return null;
58  
59  		try {
60  			BufferedReader in=new BufferedReader(new FileReader(f));
61  			String l;
62  			java.lang.StringBuffer buff=new java.lang.StringBuffer((int)f.length());
63  			boolean first = true;
64  			while ((l=in.readLine())!=null) {
65  				if (first)
66  					first = false;
67  				else
68  					buff.append('\n');
69  				buff.append(l);
70  			}
71  			return buff.toString();
72  		} catch (Exception except) { 
73  			except.printStackTrace();
74  			return null;
75  		}
76  	}
77  	public static final void writeProperties(Properties properties, File file) throws IOException {
78  		File parentFile = file.getParentFile();
79  		if (!parentFile.exists()) parentFile.mkdirs();
80  		OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
81  		properties.store(out, file.getName());
82  		out.close();
83  	}
84  	public static final Properties readProperties(File file, boolean failIfNotExists) throws IOException {
85  		Properties properties = new Properties();
86  		if (!file.exists()) {
87  			if (failIfNotExists) {
88  				return null;
89  			}
90  		} else {
91  			InputStream in = new BufferedInputStream(new FileInputStream(file));
92  			properties.load(in);
93  			in.close();
94  		}
95  		return properties;
96  	}
97  	private static final Pattern charsetPattern = Pattern.compile(";\\s*charset\\s*=\\s*([\\w-_]+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
98  	public static final String readText(URL u) throws IOException {
99  		if (u == null) return null;
100 
101 		String encoding = null;
102 		URLConnection con = u.openConnection();
103 //		if (con instanceof HttpsURLConnection) {
104 //			((HttpsURLConnection)con).setHostnameVerifier(new HostnameVerifier() {
105 //				public boolean verify(String hostname, SSLSession session) {
106 //					return true;
107 //				}
108 //			});
109 //		}
110 		if (con instanceof HttpURLConnection) {
111 			String contentType = con.getContentType();
112 			encoding = RegexUtils.findFirst(contentType, charsetPattern, 1);
113 		}
114 		InputStream in = con.getInputStream();
115 		String text = readText(in, encoding);
116 		in.close();
117 		return text;
118 	}
119 	static Pattern[] embeddedCharsetPatterns = new Pattern[] {
120 		Pattern.compile("CONTENT\\s*=\\s*\"text/\\w+;\\s*charset\\s*=\\s*([^\";\\s]+)\\s*\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL),
121 		Pattern.compile("<?\\s*xml\\s+[^>]*encoding\\s*=\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL),
122 	};
123 	private static String readText(InputStream in, String encoding) throws IOException {
124 		if (in == null)
125 			return null;
126 
127 		if (encoding == null) {
128 			ByteArrayOutputStream bout = new ByteArrayOutputStream();
129 			IOUtils.readWrite(in, bout);
130 			byte[] bytes = bout.toByteArray();
131 			String ascii = new String(bytes, "ascii");
132 			
133 			for (Pattern charsetPat : embeddedCharsetPatterns) {
134 				encoding = RegexUtils.findFirst(ascii, charsetPat, 1);
135 				if (encoding != null)
136 					break;
137 			}
138 			if (encoding != null) {
139 				try {
140 					return new String(bytes, encoding);
141 				} catch (UnsupportedEncodingException ex) {
142 					ex.printStackTrace();
143 				}
144 			}
145 			return new String(bytes);
146 		} else {
147 		
148 			BufferedReader rin = new BufferedReader(encoding == null ? new InputStreamReader(in) : new InputStreamReader(in, encoding));
149 			String l;
150 			StringBuffer buff=new StringBuffer();
151 			boolean first = true;
152 			while ((l = rin.readLine()) != null) {
153 				if (first)
154 					first = false;
155 				else
156 					buff.append('\n');
157 				buff.append(l);
158 			}
159 			return buff.toString();
160 		}
161 	}
162 	public static final String readText(InputStream in) throws IOException {
163 		return readText(in, null);
164 	}
165 	public static final List<String> readLines(String s) throws IOException {
166 		return readLines(new FileReader(s));
167 	}
168 	public static final List<String> readLines(URL u) throws IOException {
169 		InputStream in = u.openStream();
170 		List<String> r = readLines(in);
171 		in.close();
172 		return r;
173 	}
174 	public static final List<String> readLines(InputStream in) throws IOException {
175 		if (in == null)
176 			return null;
177 		List<String> r = readLines(new InputStreamReader(in));
178 		in.close();
179 		return r;
180 	}
181 	public static final List<String> readLines(Reader r) throws IOException {
182 		List<String> v=new ArrayList<String>();
183 		BufferedReader in=new BufferedReader(r);
184 		String l;
185 		while ((l=in.readLine())!=null) //if (!(l=l.trim()).equals("")) 
186 			v.add(l);
187 		return v;
188 	}
189 	public static final String[] readLinesArray(String s) throws IOException {
190 		List<String> v=readLines(s);
191 		String ret[]=new String[v.size()];
192 		int i=0;
193 		for (String line : v) {
194 			ret[i++]=line;
195 		}
196 		return ret;
197 	}
198 }