Java Text File Read readTextFile(final String path, final String enc)

Here you can find the source of readTextFile(final String path, final String enc)

Description

read Text File

License

Open Source License

Declaration

public static String readTextFile(final String path, final String enc) throws Exception 

Method Source Code

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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {

    public static String readTextFile(final String path, final String enc) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {//from   ww  w . j a  v  a2 s  .  c o m
            File f = new File(path);
            if (f.exists()) {
                FileInputStream is = new FileInputStream(path);
                try {
                    copyStream(is, os);
                } finally {
                    is.close();
                }
            } else {
                return null;
            }
        } finally {
            os.close();
        }
        return new String(os.toByteArray(), enc);
    }

    public static void copyStream(final InputStream is, final OutputStream os) throws IOException {
        byte[] buf = new byte[16 * 1024];
        while (true) {
            int len = is.read(buf);
            if (len <= 0) {
                break;
            }
            os.write(buf, 0, len);
        }
    }

    public static void copyStream(final InputStream is, final OutputStream os, final boolean close)
            throws IOException {
        try {
            try {
                copyStream(is, os);
            } finally {
                if (close) {
                    os.close();
                }
            }
        } finally {
            if (close) {
                is.close();
            }
        }
    }
}

Related

  1. loadAsString(String location)
  2. readFile(String filePath)
  3. readFile(String path)
  4. readTextFile(File file, int max, String ellipsis)
  5. readTextFile(final DataInputStream is)
  6. readTextFile(InputStream inStream)
  7. readTextFile(String fileName)
  8. readTextFile(String fn)
  9. readTextFileFast(final File file)