Tuesday, November 19, 2013

Read text file with InputStream of getClass().getResourceAsStream()

This example show how to read text from InputStream of getClass().getResourceAsStream(src). Where src is the text file inside package.


package java_readfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_ReadFile {

    String src = "song.txt";

    public static void main(String[] args) {

        Java_ReadFile java_ReadFile = new Java_ReadFile();
        java_ReadFile.readFile();
    }

    private void readFile() {
        StringBuilder stringBuilder = new StringBuilder();

        InputStream inputStream = getClass().getResourceAsStream(src);

        if (inputStream == null) {
            System.out.println("inputStream == null");
        } else {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            
            try {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                System.out.print(stringBuilder.toString());
            } catch (IOException ex) {
                Logger.getLogger(Java_ReadFile.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        System.out.println("- Finish -");
    }
}

No comments:

Post a Comment