Java File to String fileToString(File file)

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

Description

Reads a File and places the contents into a collection of Strings.

License

Open Source License

Parameter

Parameter Description
the file to read

Return

the Collection of Strings or null on failure

Declaration

public static Collection<String> fileToString(File file) 

Method Source Code


//package com.java2s;
/*//w  ww.j a  v a 2s . c  o  m
 * This file is part of SpoutAPI (http://www.getspout.org/).
 *
 * SpoutAPI 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, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SpoutAPI 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.Collection;

import java.util.LinkedList;

public class Main {
    /**
     * Reads a File and places the contents into a collection of Strings.
     *
     * Each line in the File is converted into a String.
     *
     * Iterators on the List will iterate through the Strings in the order the
     * lines appear in the file
     *
     * @param the file to read
     * @return the Collection of Strings or null on failure
     */
    public static Collection<String> fileToString(File file) {

        BufferedReader br;

        try {
            br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException fnfe) {
            return null;
        }

        String line;

        try {
            Collection<String> strings = new LinkedList<String>();
            while ((line = br.readLine()) != null) {
                strings.add(line);
            }
            return strings;
        } catch (IOException ioe) {
            return null;
        } catch (NumberFormatException nfe) {
            return null;
        } finally {
            try {
                br.close();
            } catch (IOException ioe) {
            }
        }
    }
}

Related

  1. fileToString(File file)
  2. fileToString(File file)
  3. fileToString(File file)
  4. fileToString(File file)
  5. fileToString(File file)
  6. fileToString(File file)
  7. fileToString(File file, int max)
  8. fileToString(File file, String charsetName)
  9. fileToString(File file, String charsetName)