Java Text File Load loadTextFile(String fileName)

Here you can find the source of loadTextFile(String fileName)

Description

load Text File

License

Open Source License

Declaration

public static String loadTextFile(String fileName) throws IOException 

Method Source Code


//package com.java2s;
/*//from   ww w.  ja v a  2s .c  om
(C) 2007 Stefan Reich (jazz@drjava.de)
This source file is part of Project Prophecy.
For up-to-date information, see http://www.drjava.de/prophecy
    
This source file is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
*/

import java.io.*;

public class Main {
    public final static String charsetForTextFiles = "UTF8";

    public static String loadTextFile(String fileName) throws IOException {
        return loadTextFile(fileName, null);
    }

    public static String loadTextFile(String fileName, String defaultContents) throws IOException {
        if (!new File(fileName).exists())
            return defaultContents;

        FileInputStream fileInputStream = new FileInputStream(fileName);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
        return loadTextFile(inputStreamReader);
    }

    public static String loadTextFile(Reader reader) throws IOException {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line;
            while ((line = bufferedReader.readLine()) != null)
                builder.append(line).append('\n');
        } finally {
            reader.close();
        }
        return builder.length() == 0 ? "" : builder.substring(0, builder.length() - 1);
    }

    public static String loadTextFile(File file) throws IOException {
        return loadTextFile(file.getPath());
    }
}

Related

  1. loadText(String path)
  2. loadTextFile(File file)
  3. loadTextFile(File textFile)
  4. loadTextFile(final String filePath)
  5. loadTextFile(String fileFullPath)
  6. loadTextFile(String fileName)
  7. loadTextFile(String filename)
  8. loadTextFile(String filename, int maxLines)
  9. loadTextFileAsLines(String fileName)