Java中InputStream輸入流轉String字符串的操作


一、InputStream類中read方法

package com.zhiyin.test;

import java.io.InputStream;

public class MyTest {
    public static void main(String[] args) {
        MyTest myTest = new MyTest();
        myTest.test();
    }

    public void test() {
        try {
            // 讀取測試文件
            MyTest test = new MyTest();
            InputStream is = test.getClass().getResourceAsStream("testFile.txt");
            byte[] byteArr = new byte[is.available()];
            is.read(byteArr);
            String str = new String(byteArr);
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、開源工具類IOUtils中toString方法

maven項目中pom.xml文件里引入依賴:

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

演示代碼如下:

package com.zhiyin.test;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;

public class MyTest {
    public static void main(String[] args) {
        MyTest myTest = new MyTest();
        myTest.test();
    }

    public void test() {
        try {
            // 讀取測試文件
            MyTest test = new MyTest();
            InputStream is = test.getClass().getResourceAsStream("testFile.txt");
            
            String str = IOUtils.toString(is);
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、開源工具類CharStreams中toString方法

maven項目中pom.xml文件里引入依賴:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.1-jre</version>
</dependency>

演示代碼如下:

package com.zhiyin.test;

import com.google.common.io.CharStreams;

import java.io.InputStream;
import java.io.InputStreamReader;

public class MyTest {
    public static void main(String[] args) {
        MyTest myTest = new MyTest();
        myTest.test();
    }

    public void test() {
        try {
            // 讀取測試文件
            MyTest test = new MyTest();
            InputStream is = test.getClass().getResourceAsStream("testFile.txt");
            // 字節輸入流轉字符輸入流
            InputStreamReader isr = new InputStreamReader(is);
            // CharStreams.toString()方法轉換字符輸入流
            String str = CharStreams.toString(isr);
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM