Java FileReader Create readTextFile(String path)

Here you can find the source of readTextFile(String path)

Description

Reads the specified text file and returns their contents in a String

License

Open Source License

Parameter

Parameter Description
path Path to the file to read. It is created if it doesn't exist

Exception

Parameter Description
IOException an exception

Return

Contents of the specified file

Declaration

public static String readTextFile(String path) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w w  w  .ja  v a2 s  . c o  m
     
 This file is part of Subclient.
     
 Subclient is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
     
 Subclient is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.
     
 You should have received a copy of the GNU General Public License
 along with Subclient. If not, see <http://www.gnu.org/licenses/>.
     
 Copyright 2012, 2013 Alejandro Celaya Alastru?
     
 */

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;

import java.io.IOException;

public class Main {
    /**
     * Reads the specified text file and returns their contents in a String
     * @param path Path to the file to read. It is created if it doesn't exist
     * @return Contents of the specified file
     * @throws IOException
     */
    public static String readTextFile(String path) throws IOException {
        // Read the current contents of the specified file
        File file = new File(path);
        // If the file does not exist, create it
        if (!file.exists()) {
            file.createNewFile();
            return "";
        }

        // Read the file and keep the content
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder content = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null)
            content.append(line);
        reader.close();

        // Return the content of the file
        return content.toString();
    }
}

Related

  1. readTextFile(String fileName, String enc)
  2. readTextFile(String filePath)
  3. readTextFile(String filePath)
  4. readTextFile(String filePath)
  5. readTextFile(String fullPathFilename)
  6. readTextFile(String path)
  7. readTextFile(String text_file_name)
  8. readTextFile(String text_file_name)
  9. readTextFileAsList(File file)