Java InputStreamReader Read readFileLineByLine(final File filePath)

Here you can find the source of readFileLineByLine(final File filePath)

Description

read File Line By Line

License

Apache License

Declaration

public static Iterator<String> readFileLineByLine(final File filePath) throws java.io.IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.Iterator;

import java.util.zip.GZIPInputStream;

public class Main {
    public static Iterator<String> readFileLineByLine(final File filePath) throws java.io.IOException {
        return new Iterator<String>() {

            // Open the file that is the first
            // command line parameter
            InputStream fstream = new FileInputStream(filePath);
            {//from w  w  w . j  a  va2s  . c  om
                if (filePath.getName().endsWith(".gz")) {
                    // Automatically unzip zipped files.
                    fstream = new GZIPInputStream(fstream);
                }
            }

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String next = br.readLine();

            @Override
            public boolean hasNext() {

                final boolean result = (next != null);
                if (!result) {
                    try {
                        br.close();
                    } catch (final IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                return result;
            }

            @Override
            public String next() {
                final String result = next;
                try {
                    next = br.readLine();
                } catch (final IOException e) {
                    throw new RuntimeException(e);
                }
                return result;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}

Related

  1. readFileFromDisk(String filepath)
  2. readFileFromResource(@SuppressWarnings("rawtypes") Class refClass, String filePath)
  3. readFileFromResource(String filename)
  4. readFileIntoLines(File file)
  5. readFileIntoLinesOfLongs(File file)
  6. readFileList(File file)
  7. readFileOneLine(String filename, String keyInLine)
  8. readFileOrResource(String source)
  9. readFiles(String[] files, String encoding)