Skip to content

Instantly share code, notes, and snippets.

@miere
Created September 30, 2014 13:02
Show Gist options
  • Select an option

  • Save miere/194a8e82af4cfdaf46f5 to your computer and use it in GitHub Desktop.

Select an option

Save miere/194a8e82af4cfdaf46f5 to your computer and use it in GitHub Desktop.
package tests.helper;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Class with helper methods to read file content from your classpath.
* It is especially useful when need to compare big string output with
* a file that contains the expected response.
*/
public class Files {
/**
* Read a file placed in same package you call this method.
*/
static String readInSamePackage( final String fileName ) {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
final StackTraceElement calleeElement = stackTrace[1];
final String packageName = calleeElement.getClassName().replaceAll( "\\.[^\\.]+$", "" );
final String directory = packageName.replace( '.', File.separatorChar );
return read( directory + File.separatorChar + fileName );
}
/**
* Read a file.
*/
static String read( final String fileName ) {
try {
final InputStreamReader reader = openFileAsStream( fileName );
final StringBuilder string = new StringBuilder();
final char[] buffer = new char[1024];
int readbytes = 0;
while ( ( readbytes = reader.read( buffer ) ) >= 0 )
string.append( buffer, 0, readbytes );
return string.toString();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
private static InputStreamReader openFileAsStream( final String fileName ) {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return new InputStreamReader( classLoader.getResourceAsStream( fileName ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment