读取文件中内容转换成字符串

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package com.lieni.ruyu.api.xmlTool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class ReadTextToString {
    public static void main(String[] args) {
        String fileName = "C:\\Users\\rysh101\\Desktop\\工作资料\\xxx.xml";
        String readToString = readToString(fileName);
        System.out.println(readToString);
    }

    public static String readToString(String fileName) {
        String encoding = "GBK";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }
}
 

转载于:https://my.oschina.net/newdeng/blog/1859521

你可能感兴趣的:(读取文件中内容转换成字符串)