get String From UTF File - Java java.io

Java examples for java.io:File UTF

Description

get String From UTF File

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Main {
    public static void main(String[] argv) {
        String fileName = "java2s.com";
        System.out.println(getStringFromUTF8File(fileName));
    }//from  w ww  .j ava  2s .  c om

    public static String getStringFromUTF8File(String fileName) {
        try {
            File file = new File(fileName);
            InputStream is = new FileInputStream(file);
            return read(new InputStreamReader(is, "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getStringFromUTF8File(InputStream is) {
        try {
            return read(new InputStreamReader(is, "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static String read(InputStreamReader isr) throws IOException {
        StringBuffer buffer = new StringBuffer();
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1) {
            buffer.append((char) ch);
        }
        in.close();
        return buffer.toString();
    }
}

Related Tutorials