Given the path to a file in the specified encoding, returns a single string with the contents of that file. - Java File Path IO

Java examples for File Path IO:Path

Description

Given the path to a file in the specified encoding, returns a single string with the contents of that file.

Demo Code

/**/*from   ww  w.  j  av a  2s. co  m*/
 * Copyright (c) 2009 DITA2InDesign project (dita2indesign.sourceforge.net)  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.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Main{
    /**
     * Given the path to a file in the specified encoding, returns a single string
     * with the contents of that file.
     *
     * @param filePath The local path to the file
     *
     * @param encoding The encoding name: UTF8, UTF16, etc.
     */
    static public String readUnicodeFile(String filePath, String encoding)
            throws DataUtilException {
        // This code copied directly from the Java tutorial
        StringBuffer buffer = new StringBuffer();
        try {
            FileInputStream fis = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(fis, encoding);
            Reader in = new BufferedReader(isr);
            int ch;
            while ((ch = in.read()) > -1) {
                buffer.append((char) ch);
            }
            in.close();
            return buffer.toString();
        } catch (IOException e) {
            throw new DataUtilException("IOException: " + e.getMessage()
                    + " for file '" + filePath + "'", e);
        }
    }
}

Related Tutorials