Java Text File Read by Encode readFileAsString(InputStream input, OutputStream output, String inputEncoding)

Here you can find the source of readFileAsString(InputStream input, OutputStream output, String inputEncoding)

Description

read File As String

License

Open Source License

Declaration

public static String readFileAsString(InputStream input, OutputStream output, String inputEncoding)
            throws Exception 

Method Source Code


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

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static String readFileAsString(InputStream input, OutputStream output, String inputEncoding)
            throws Exception {
        return replaceInFile(input, output, inputEncoding, null);
    }/*from  www  .  j  a  v  a2 s .com*/

    public static String replaceInFile(InputStream input, OutputStream output, String inputEncoding,
            Map<String, String> replacements) throws Exception {
        byte[] buffer = new byte[input.available()];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(input);
            Reader reader = (inputEncoding != null) ? new InputStreamReader(bis, inputEncoding)
                    : new InputStreamReader(bis);
            bis.read(buffer);
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException ignored) {
                }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(buffer);
        if (replacements != null) {
            String text = baos.toString();
            for (Entry<String, String> replacement : replacements.entrySet()) {
                text = text.replaceAll(replacement.getKey(), replacement.getValue());
            }
            baos.reset();
            baos.write(text.getBytes());
        }
        baos.writeTo(output);

        return baos.toString();
    }

    public static void replaceAll(File fileName, String inputEncoding, Map<String, String> replacements)
            throws Exception {
        InputStream in = new FileInputStream(fileName);
        FileOutputStream fos = new FileOutputStream(fileName);
        replaceInFile(in, fos, inputEncoding, null);
    }
}

Related

  1. getFileContentAsString(File file, String encoding)
  2. getFileContentAsString(String filePath, String fileEncoding)
  3. getFileContents(InputStream stream, String encoding)
  4. getFileContents(String filename, String encoding)
  5. readFileAsString(final File f, final String encoding)