Skip to content

Instantly share code, notes, and snippets.

@jyeary
Last active August 8, 2017 00:22
Show Gist options
  • Save jyeary/d5ef76d1d53f131e488a7d83e79d491b to your computer and use it in GitHub Desktop.
Save jyeary/d5ef76d1d53f131e488a7d83e79d491b to your computer and use it in GitHub Desktop.
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment