Here you can find the source of getFileContent(File file)
Parameter | Description |
---|---|
file | the file |
Parameter | Description |
---|---|
Exception | the exception if error occurred |
public static String getFileContent(File file) throws Exception
//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; } } }