Java Text File Read Line readLinesTrimmedNoComment(final String fileName, final String commentString)

Here you can find the source of readLinesTrimmedNoComment(final String fileName, final String commentString)

Description

read Lines Trimmed No Comment

License

Apache License

Declaration

public static String[] readLinesTrimmedNoComment(final String fileName, final String commentString)
            throws FileNotFoundException, IOException 

Method Source Code


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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.ArrayList;

public class Main {
    public static String[] readLinesTrimmedNoComment(final String fileName, final String commentString)
            throws FileNotFoundException, IOException {
        File wtsFile = new File(fileName);
        if (!wtsFile.isFile())
            throw new FileNotFoundException("Cannot find file for reading: " + fileName);

        FileInputStream fin = null;
        BufferedReader in = null;
        try {/*www . j  a va 2 s.  c o m*/
            fin = new FileInputStream(wtsFile);
            in = new BufferedReader(new InputStreamReader(fin));
        } catch (IOException e) {
            throw new IOException("IOException during reading of text file: " + fileName);
        }

        return readLinesTrimmedNoCommmentFromBufferedReader(in, commentString);
    }

    private static String[] readLinesTrimmedNoCommmentFromBufferedReader(final BufferedReader in,
            final String commentString) throws IOException {
        ArrayList<String> lineList = new ArrayList<String>();
        String line;
        while (in.ready()) {
            line = in.readLine();
            if (line == null) {
                continue;
            }

            line = line.trim();

            if (line.startsWith(commentString))
                continue;

            if (line.contains(commentString)) {
                String[] items = line.split(commentString);
                line = items[0].trim();
            }

            lineList.add(line);
        }

        in.close();

        String[] lines = new String[lineList.size()];

        lineList.toArray(lines);

        return lines;
    }
}

Related

  1. readLinesAsList(String filename)
  2. readLinesFileSimple(final File inFile, final int prefixMode, final String prefix)
  3. readLinesFromCommand(String command[], List buffer)
  4. readLinesNoComments(String fileName)
  5. readLinesRaw(final File inFile)
  6. readLinesWithPattern(File file, Pattern pattern)