集册 Java实例教程 给定指定编码的文件路径,返回包含该文件内容的单个字符串。

给定指定编码的文件路径,返回包含该文件内容的单个字符串。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

393
给定指定编码格式的文件路径,返回包含该文件内容的单个字符串。

/**

 * 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. 

 *//*来 自 n o w j a v a . c o m - 时  代  Java*/

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;
/*
n o w  j a v a  . c o m
*/

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);

            
展开阅读全文