Java File Content Read getFileContent(File file)

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

Description

Reads a file content and return it as String.

License

Apache License

Parameter

Parameter Description
file the file

Exception

Parameter Description
Exception the exception if error occurred

Return

the file content

Declaration

public static String getFileContent(File file) throws Exception 

Method Source Code


//package com.java2s;
/*/*from  w  ww. j  a v a2 s.c om*/
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.util.Scanner;

public class Main {
    /**
     * Reads a file content and return it as String. Returns <code>NULL</code>
     * if file doesn't exist and empty String if file exists but is empty.
     * @param file the file
     * @return the file content
     * @throws Exception the exception if error occurred
     */
    public static String getFileContent(File file) throws Exception {
        Scanner scanner = null;
        String content = null;
        Exception reThrow = null;
        if (file != null && file.length() > 0) {
            try {
                scanner = new Scanner(file);
                content = scanner.useDelimiter("\\A").next();
            } catch (Exception e) {
                reThrow = e;
            } finally {
                if (scanner != null) {
                    try {
                        scanner.close();
                    } catch (Exception e) {
                    }
                }
            }
        } else if (file != null && file.length() == 0) {
            content = "";
        }
        if (reThrow != null) {
            throw reThrow;
        } else {
            return content;
        }
    }
}

Related

  1. getFileContent(File file)
  2. getFileContent(File file)
  3. getFileContent(File file)
  4. getFileContent(File file)
  5. getFileContent(File file)
  6. getFileContent(String filename)
  7. getFileContent(String filename)
  8. getFileContent(String fileName)
  9. getFileContent(String filename)