常用转换工具

做~自己de王妃 提交于 2019-12-10 19:57:20

读取文件转string

    private static String readString3() {
        String str = "";
        File file = new File(path);
        try {
            FileInputStream in = new FileInputStream(file);
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer, "utf-8");
        } catch (IOException e) {

            return null;
        }
        return str;
    }

输入流转document

public static Document isToDoc(InputStream is) throws Exception{
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);     
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

inputstream转json

public JSONObject isToJson(InputStream is) throws Exception {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            byteArrayOutputStream.write(i);
        }
        String s = byteArrayOutputStream.toString();
        JSONObject jsonObject = XML.toJSONObject(s);
        return jsonObject;
    }

复制流

//流正常只能使用一次
private static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!