Java Scanner Read readFile(String filename)

Here you can find the source of readFile(String filename)

Description

Reads a certain file of a path.

License

Open Source License

Parameter

Parameter Description
filename the path the file to read

Return

content as the read file

Declaration

public static String readFile(String filename) 

Method Source Code

//package com.java2s;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main {
    /**// w w w  .  j ava2s. c  o m
     * Reads a certain file of a path.
     *
     * @param filename the path the file to read
     * @return content as the read file
     */
    public static String readFile(String filename) {
        StringBuilder content = new StringBuilder();

        try {
            String NL = System.getProperty("line.separator");
            Scanner scanner = new Scanner(new FileInputStream(filename));

            try {
                while (scanner.hasNextLine()) {
                    content.append(scanner.nextLine() + NL);
                }
            } finally {
                scanner.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return content.toString();
    }
}

Related

  1. readFile(File file)
  2. readFile(File input)
  3. readFile(File path)
  4. readFile(final File f)
  5. readFile(String file_name)
  6. readFile(String fileName)
  7. readFile(String fileName)
  8. readFile(String fileName)
  9. readFile(String filePath)