Quantcast
Viewing all articles
Browse latest Browse all 36

Answer by Ajk for How do I create a Java string from the contents of a file?

I cannot comment other entries yet, so I'll just leave it here.

One of best answers here (https://stackoverflow.com/a/326448/1521167):

private String readFile(String pathname) throws IOException {File file = new File(pathname);StringBuilder fileContents = new StringBuilder((int)file.length());Scanner scanner = new Scanner(file);String lineSeparator = System.getProperty("line.separator");try {    while(scanner.hasNextLine()) {                fileContents.append(scanner.nextLine() + lineSeparator);    }    return fileContents.toString();} finally {    scanner.close();}}

still has one flaw. It always puts new line char in the end of string, which may cause some weirds bugs. My suggestion is to change it to:

    private String readFile(String pathname) throws IOException {    File file = new File(pathname);    StringBuilder fileContents = new StringBuilder((int) file.length());    Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));    String lineSeparator = System.getProperty("line.separator");    try {        if (scanner.hasNextLine()) {            fileContents.append(scanner.nextLine());        }        while (scanner.hasNextLine()) {            fileContents.append(lineSeparator + scanner.nextLine());        }        return fileContents.toString();    } finally {        scanner.close();    }}

Viewing all articles
Browse latest Browse all 36

Trending Articles