Here you can find the source of readTextFile(final URL resource)
Parameter | Description |
---|---|
resource | The resource from which to read the text. |
Parameter | Description |
---|---|
IOException | When read fails. |
public static String readTextFile(final URL resource) throws IOException
//package com.java2s; /*//from w ww .j a va2 s. c om * Copyright (C) 2011 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class Main { /** * Reads a text file (UTF-8 encoding) from the specified resource. * * @param resource * The resource from which to read the text. * @return The text. * @throws IOException * When read fails. */ public static String readTextFile(final URL resource) throws IOException { if (resource == null) throw new IOException("Resource not found"); try (final InputStream stream = resource.openStream()) { return readTextFile(stream); } } /** * Reads a text file (UTF-8 encoding) from the specified stream. * * @param resource * The resource from which to read the text. * @return The text. * @throws IOException * When read fails. */ public static String readTextFile(final InputStream resource) throws IOException { return new String(readFile(resource), "UTF-8"); } /** * Reads data from a file. * * @param filename * The filename. Can be '-' for reading from stdin. * @return data The read data. * @throws IOException * When read fails. */ public static byte[] readFile(final String filename) throws IOException { if (filename.equals("-")) return readFile(System.in); try (final InputStream stream = new FileInputStream(filename)) { return readFile(stream); } } /** * Reads data from a stream. * * @param stream * The stream from which to read the data. * @return data The read data. * @throws IOException * When read fails. */ public static byte[] readFile(final InputStream stream) throws IOException { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); copy(stream, bytes); return bytes.toByteArray(); } /** * Copies data from input stream to output stream. * * @param input * The input stream * @param output * The output stream * @throws IOException * When copying fails. */ public static void copy(final InputStream input, final OutputStream output) throws IOException { final byte[] buffer = new byte[8192]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } } }