您的位置:首页 > 编程语言 > Java开发

Java读取一个文本文件拼接成一个字符串(readFileToString)

2018-02-13 15:15 471 查看
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.Test;

public class Demo {// 使用示例
@Test
public void testName1() throws Exception {
String filePath = "D:\\测试数据\\测试数据.json";

String jsonString = readFileToString(filePath);

System.out.println(jsonString);

System.out.println("done.....");
}

public static String readFileToString(String path) {
// 定义返回结果
String jsonString = "";

BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"));// 读取文件
String thisLine = null;
while ((thisLine = in.readLine()) != null) {
jsonString += thisLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException el) {
}
}
}

// 返回拼接好的JSON String
return jsonString;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐