Java File to String fileToString(File file)

Here you can find the source of fileToString(File file)

Description

Reads the entire file content.

License

Open Source License

Parameter

Parameter Description
file the file

Exception

Parameter Description
FileNotFoundException thrown file does not exists

Return

the content of the file

Declaration

public static String fileToString(File file) throws FileNotFoundException 

Method Source Code


//package com.java2s;
/*/*  w ww .  j  a va  2  s. c  om*/
 * dataZ - Test Support For Data Stores.
 *
 * Copyright 2014-2017 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.*;

public class Main {
    /**
     * Reads the entire file content.
     *
     * @param file the file
     * @return the content of the file
     * @throws FileNotFoundException thrown file does not exists
     */
    public static String fileToString(File file) throws FileNotFoundException {
        return inputStreamToString(new FileInputStream(file));
    }

    /**
     * Converts the {@code inputStream} to String. The {@code inputStream} will be consumed.
     *
     * @param inputStream the input stream
     * @return the content as string.
     */
    public static String inputStreamToString(InputStream inputStream) {
        final StringBuilder output = new StringBuilder();
        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while (null != (line = reader.readLine())) {
                output.append(line).append('\n');
            }
        } catch (IOException ex) {
            throw new RuntimeException("Caught IO Exception", ex);
        }

        return output.toString();
    }
}

Related

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