Here you can find the source of readAllLines(String path)
Parameter | Description |
---|---|
path | path of file |
Parameter | Description |
---|---|
IOException | If a non UTF-8 character is found, this exception isthrown. |
public static List<String> readAllLines(String path) throws IOException
//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; } }