|
package com.bluelotussoftware.io; |
|
|
|
import java.io.ByteArrayInputStream; |
|
import java.io.DataInputStream; |
|
import java.io.IOException; |
|
import java.io.InputStream; |
|
import java.io.UnsupportedEncodingException; |
|
|
|
/** |
|
* |
|
* @author John Yeary <jyeary@bluelotussoftware.com> |
|
* @version 2.0.0 |
|
*/ |
|
public class IOUtils { |
|
|
|
/** |
|
* This reads an {@link InputStream} and converts it to a {@link String}. |
|
* |
|
* @param is The stream to convert. |
|
* @return The converted {@link InputStream} to text. |
|
* @since 1.0.0 |
|
*/ |
|
public String parseISToString(InputStream is) { |
|
DataInputStream din = new DataInputStream(is); |
|
StringBuilder sb = new StringBuilder(); |
|
try { |
|
String line = null; |
|
while ((line = din.readLine()) != null) { |
|
sb.append(line).append("\n"); |
|
} |
|
} catch (IOException ex) { |
|
ex.printStackTrace(System.err); |
|
} finally { |
|
try { |
|
is.close(); |
|
} catch (IOException ex) { |
|
} |
|
} |
|
return sb.toString(); |
|
} |
|
|
|
/** |
|
* Converts a {@link String} into an {@link InputStream} |
|
* |
|
* @param text The text to convert to an {@link InputStream}. |
|
* @return An {@link InputStream} from the text value provided. |
|
* @since 1.0.0 |
|
*/ |
|
public InputStream parseStringToIS(String text) { |
|
if (text == null) { |
|
return null; |
|
} |
|
text = text.trim(); |
|
java.io.InputStream in = null; |
|
try { |
|
in = new ByteArrayInputStream(text.getBytes("UTF-8")); |
|
} catch (UnsupportedEncodingException ex) { |
|
ex.printStackTrace(System.err); |
|
} |
|
return in; |
|
} |
|
|
|
/** |
|
* This reads an {@link InputStream} and converts it to a {@link String}. |
|
* |
|
* @param is The stream to convert. |
|
* @return The converted {@link InputStream} to UTF-8 text. |
|
* @since 2.0.0 |
|
*/ |
|
public String toString(final InputStream is) { |
|
StringBuilder sb = new StringBuilder(); |
|
try (DataInputStream din = new DataInputStream(is)) { |
|
String line; |
|
while ((line = din.readUTF()) != null) { |
|
sb.append(line); |
|
} |
|
} catch (IOException ex) { |
|
ex.printStackTrace(System.err); |
|
} |
|
return sb.toString(); |
|
} |
|
|
|
/** |
|
* Converts a {@link String} into an {@link InputStream} |
|
* |
|
* @param text The text to convert to an {@link InputStream}. |
|
* @return A UTF-8 encoded {@link InputStream} from the text value provided. |
|
* @since 2.0.0 |
|
*/ |
|
public InputStream toInputStream(final String text) { |
|
if (text == null || text.isEmpty()) { |
|
return null; |
|
} |
|
|
|
try (InputStream in = new ByteArrayInputStream(text.getBytes("UTF-8"))) { |
|
return in; |
|
} catch (UnsupportedEncodingException ex) { |
|
ex.printStackTrace(System.err); |
|
} catch (IOException ex) { |
|
ex.printStackTrace(System.err); |
|
} |
|
return null; |
|
} |
|
} |