java 读取文件内容,两种方式system.out.println()结果差别

Richard_reallife 2018-09-11 04:56:02

public static void checkSystemLog(String logFile) {
//思路:读取文件内容,查询是否有相同的异常信息,查询到的信息输出到txt文件中
//1.声明一个输入流对象
FileInputStream fileInput = null;
File file = new File(logFile);
try {
// //2.通过file对象构建一个流对象
// fileInput = new FileInputStream(file);
// //3.设置字节数组,1024只是一个习惯
// byte[] data = new byte[1024];
// StringBuffer stb = new StringBuffer();
// int len;//用来存储read(byte[] b)方法的返回值,代表每次读入的字节个数;当因为到达文件末尾而没有字节读入时,返回-1
// while((len=fileInput.read(data))!=-1){
// stb.append(data);
// }
// String string = new String(stb.toString().getBytes(),"GBK");
// System.out.println("string"+string);
// 通过File对象构建一个流对象
fileInput = new FileInputStream(file);
// 读取数据,并将读取的数据存储在数组中
byte[] data = new byte[(int)file.length()];
// 读取流中的第一个字节数据
int n = fileInput.read();
// 读取的游标位置
int i = 0;
// 判断是否读到最后一个字符
while(n != -1) {
data[i] = (byte)n;
i++;
n = fileInput.read();
}
String rs = new String(data, "GBK");
System.out.println(rs);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

该方法传入的文件地址指向的是字符型文件。注释掉的方法,最后输出的结果为string[B@7fbe847c。而接下来的方法可以得到文件的内容,这是为什么呢,求大神指教一下!
...全文
331 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
潘少博 2018-09-12
  • 打赏
  • 举报
回复
stb.append(new String(data, 0, leng)); 这句话的时候,你已经使用编码了啊,这里已经乱了,不是最后的编码导致的。 解决方法: 你要读取的是一个流,那就别放到StringBuffer中,而是应该放到一个byte[]中,最后再new String的时候转义
Richard_reallife 2018-09-12
  • 打赏
  • 举报
回复

//2.通过file对象构建一个流对象
fileInput = new FileInputStream(file);
//3.设置字节数组,1024只是一个习惯
byte[] data = new byte[1024];
StringBuffer stb = new StringBuffer();
int leng;//用来存储read(byte[] b)方法的返回值,代表每次读入的字节个数;当因为到达文件末尾而没有字节读入时,返回-1
while((leng=fileInput.read(data))!=-1){
stb.append(new String(data, 0, leng));
}
String string = new String(stb.toString().getBytes(),"GBK");
System.out.println("string"+string);

我后来改成了这种方式,但出现的是乱码,这是编码类型的问题,还是什么啊?
wildyy 2018-09-11
  • 打赏
  • 举报
回复
StringBuffer的append如果传byte[]相当于传Object,实际上调用String的valueOf(Object),即调用byte[]的toString,返回的是地址

51,386

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧