Created
September 30, 2014 13:02
-
-
Save miere/194a8e82af4cfdaf46f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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