/** * 读取文件 * @param filename * @return * @throws IOException */ public static byte[] readFile(String filename) throws IOException { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = null; if (filename.startsWith("http://")) { URL url = new URL(filename); URLDataSource uds = new URLDataSource(url); in = uds.getInputStream(); } else { in = new FileInputStream(filename); } BufferedInputStream bufferedInputStream = new BufferedInputStream(in); int len = bufferedInputStream.available(); byte[] bytes = new byte[len]; int r = bufferedInputStream.read(bytes); if (len != r) { bytes = null; throw new IOException("读取文件不正确"); } bufferedInputStream.close(); return bytes; }
protected String getFromUrl(final URL url) throws Exception { final URLDataSource dataSource = new URLDataSource(url); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), baos); return new String(baos.toByteArray(), "UTF-8"); }
public URLAttachment(String url, String fileName, ContentDisposition contentDisposition) { super(); URLDataSource uds; try { uds = new URLDataSource(new URL(url)); super.setFileName(fileName); super.setMimeType(uds.getContentType()); super.setContentDisposition(contentDisposition); super.setBytes(Streams.toByteArray(uds.getInputStream())); } catch (MalformedURLException e) { throw new AttachmentException("Wasn't able to create email attachment from URL: " + url, e); } catch (IOException e) { throw new AttachmentException("Wasn't able to create email attachment from URL: " + url, e); } }