Java File to String fileToString(File f, String encoding)

Here you can find the source of fileToString(File f, String encoding)

Description

Reads the contents of a file into a String.

License

Open Source License

Parameter

Parameter Description
f The file to read from
encoding The endcoding standard to use. (e.g. UTF-8, UTF-16)

Exception

Parameter Description
FileNotFoundException If the file specified does not exist.

Return

The contents of the file as a String.

Declaration

public static String fileToString(File f, String encoding) throws FileNotFoundException 

Method Source Code

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

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main {
    /**//from www .ja  v  a  2  s .  co  m
     * Reads the contents of a file into a String. Use with a <tt>.txt</tt> files for best results.
     * There seems to be an issue with reading in non-standard ascii characters at the moment.
     * 
     * @param f The file to read from
     * @param encoding The endcoding standard to use. (e.g. UTF-8, UTF-16)
     * 
     * @return The contents of the file as a String.
     * 
     * @throws FileNotFoundException If the file specified does not exist.
     */
    public static String fileToString(File f, String encoding) throws FileNotFoundException {
        Scanner m = new Scanner(f, encoding);
        String s = "";
        while (m.hasNextLine())
            s += m.nextLine().trim() + "\n";

        m.close();
        return s.trim();

    }
}

Related

  1. fileToString(File f)
  2. fileToString(File f)
  3. fileToString(File f)
  4. fileToString(File f)
  5. fileToString(File f)
  6. fileToString(File file)
  7. fileToString(File file)
  8. fileToString(File file)
  9. fileToString(File file)