Java File to String fileToString(String file)

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

Description

Read the contents of a file and place them in a string object.

License

Open Source License

Parameter

Parameter Description
file path to file.

Return

String contents of the file.

Declaration

public static String fileToString(String file) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from w w w  . java  2 s .  c  o m
     * Read the contents of a file and place them in a string object.
     *
     * @param file
     *            path to file.
     * @return String contents of the file.
     */
    public static String fileToString(String file) {
        String contents = "";

        File f = null;
        try {
            f = new File(file);

            if (f.exists()) {
                FileReader fr = null;
                try {
                    fr = new FileReader(f);
                    char[] template = new char[(int) f.length()];
                    fr.read(template);
                    contents = new String(template);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fr != null) {
                        fr.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contents;
    }
}

Related

  1. fileToString(final String filePath)
  2. fileToString(InputStream file)
  3. fileToString(InputStream inputStream)
  4. fileToString(String file)
  5. fileToString(String file)
  6. fileToString(String file, String encoding)
  7. FileToString(String file_name)
  8. fileToString(String fileName)
  9. fileToString(String fileName)