java怎么将一个文件中的内容读取到一个String对象里

java怎么将一个文件中的内容读取到一个String对象里,第1张

java怎么将一个文件中的内容读取到一个String对象里

以下代码分别使用了 Okio的BufferedSource和Guava的ByteStreams来读取整个文件内容到String.

package com.test;


import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;

import org.junit.Assert;

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

import okio.BufferedSource;
import okio.Okio;

public class Test {

    
    @org.junit.Test
    public void test1() {
        try {
            BufferedSource source = Okio.buffer(Okio.source(new FileInputStream("C:\aiui_phone.cfg")));
            String a1 = (source.readByteString().utf8());
            source.close();
            String a2 = new String(ByteStreams.toByteArray(new FileInputStream("C:\aiui_phone.cfg")), Charsets.UTF_8);
            Assert.assertEquals(a1, a2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

也可以使用Okio的Buffer类来实现这个功能:

    
    @org.junit.Test
    public void test2() {
        try {
            Buffer buffer = new Buffer().readFrom(new FileInputStream("C:\aiui_phone.cfg"));
            String a1 = buffer.readUtf8();
            System.out.println(a1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5676695.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存