Java File Content Read getFileContents(String filename)

Here you can find the source of getFileContents(String filename)

Description

reads contents of a (text) file and returns them as a string

License

Apache License

Declaration

public static String getFileContents(String filename) throws IOException 

Method Source Code


//package com.java2s;
/*//from w  w w.ja v  a  2s .  c o m
 Copyright (C) 2012 The Stanford MobiSocial Laboratory
    
   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.*;

import java.util.zip.GZIPInputStream;

public class Main {
    /** reads contents of a (text) file and returns them as a string */
    public static String getFileContents(String filename) throws IOException {
        BufferedReader br;
        if (filename.endsWith(".gz"))
            br = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(new FileInputStream(filename)), "UTF-8"));
        else
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        // read all the lines one by one till eof
        while (true) {
            String x = br.readLine();
            if (x == null)
                break;

            sb.append(x);
            sb.append("\n");
        }
        return sb.toString();
    }
}

Related

  1. getFileContents(File methodPatch)
  2. getFileContents(File testFile)
  3. getFileContents(final File f)
  4. getFileContents(final File file)
  5. getFileContents(String fileName)