Java Path File Read nio readAllLines(String path)

Here you can find the source of readAllLines(String path)

Description

Read file at path.

License

Open Source License

Parameter

Parameter Description
path path of file

Exception

Parameter Description
IOException If a non UTF-8 character is found, this exception isthrown.

Return

List of lines split by '\n' character.

Declaration

public static List<String> readAllLines(String path) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*  w ww .  ja  va 2s. c  o  m*/
     * Read file at path. Returns list of lines split by '\n' character.
     * 
     * Ensures file is in UTF-8.
     * 
     * @param path path of file
     * @return List of lines split by '\n' character.
     * @throws IOException If a non UTF-8 character is found, this exception is
     *             thrown.
     */
    public static List<String> readAllLines(String path) throws IOException {
        List<String> lines = new ArrayList<String>();

        CharsetEncoder encoder = Charset.forName(StandardCharsets.ISO_8859_1.toString()).newEncoder();
        boolean ignoreBOM = true; // https://en.wikipedia.org/wiki/Byte_order_mark
        BufferedReader br = null;
        String currentLine;
        int lineNumber = 1;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
            while ((currentLine = br.readLine()) != null) {
                if (!encoder.canEncode(currentLine) && !ignoreBOM) { // ensure line is UTF-8
                    throw new IOException(String.format("Line %d: \"%s\" not UTF-8", lineNumber, currentLine));
                }
                lines.add(currentLine.trim());
                ignoreBOM = false;
                ++lineNumber;
            }
        } finally {
            br.close();
        }

        return lines;
    }
}

Related

  1. read(String aPathString)
  2. read(String filePath)
  3. read(String filePath)
  4. read(String path)
  5. readAllLines(Path path)
  6. readAllLinesOrExit(Path path)
  7. readAndConsume(String filePath, Consumer consumer)
  8. readAsString(Path path)
  9. readAsString(String path)