Saturday, January 5, 2013

Removing redundant zeros from a String

string.replaceAll("^0+", "");

Removing redundant spaces from a String

string.replaceAll("\\s{2,}", "");

Escaping "$" and "\" in Java

string.replaceAll("(\\$|\\\\)", "\\\\$0");

Fixing StringIndexOutOfBoundsException on replaceAll

Exception StackTrace to String using Java

public String stringValue(Throwable e) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return result.toString();
}

Friday, January 4, 2013

Get InputStream from a given file path using Java

public InputStream fetchInputStream(String filePath) {
InputStream inputStream = this.getClass().getResourceAsStream(filePath);
if (inputStream == null) {
File file = null;
file = new File(filePath);
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return inputStream;
}

String to InputStream using Java

public InputStream toInputStream(String string) {
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
return inputStream;
}

Write InputStream to a given file path using Java

public static void writeToFile(InputStream inputStream, String filePath) {
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
writer = new BufferedWriter(new FileWriter(filePath));
int c;
while ((c = reader.read()) != -1) {
writer.write(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}