Skip to content

Instantly share code, notes, and snippets.

@ksaric
Last active January 3, 2016 20:58
Show Gist options
  • Save ksaric/8518135 to your computer and use it in GitHub Desktop.
Save ksaric/8518135 to your computer and use it in GitHub Desktop.
Usefull Java methods for reading resources.
import com.google.common.base.Charsets;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import com.google.common.io.InputSupplier;
import com.google.common.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* User: pfh(Kristijan Šarić)
*/
public class ResourcesUtil {
// Java
public static InputStream getStreamFromStringPath( Class aClass, String stringPath ) {
return aClass.getResourceAsStream( stringPath );
}
// Java + Guava
public static String getResourceToString( final String fileName ) throws IOException {
final CharSource charSource = Resources.asCharSource(
Resources.getResource( fileName ), Charsets.UTF_8
);
final StringBuilder stringBuilder = new StringBuilder();
charSource.copyTo( stringBuilder );
return stringBuilder.toString();
}
public static String getFileContents( final String fileName ) {
Preconditions.checkNotNull( fileName, "Unable to retrieve text from null." );
final File sourceFile = new File( fileName );
try {
final String fileContents = Files.toString( sourceFile, Charsets.UTF_8 );
// verify the content is valid
if ( Strings.isNullOrEmpty( fileContents ) ) {
throw new IllegalArgumentException( "Invalid file path. File content NULL or EMPTY." );
} else {
return fileContents;
}
} catch ( IOException e ) {
e.printStackTrace();
throw new IllegalArgumentException( "File loading exception. Invlid file path." );
}
}
// Java + Guava
public static String streamToString( final InputStream finalSource ) throws IOException {
final ByteSource supplier = new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return finalSource;
}
};
final CharSource charSource = supplier.asCharSource( Charsets.UTF_8 );
return charSource.read();
}
public static java.sql.Date getCurrentSqlDate() {
java.util.Calendar cal = java.util.Calendar.getInstance();
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new Date( utilDate.getTime() );
return sqlDate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment