你好,我是一名计算机专业的研究生,我有一个简单的问题,不知道为什么,请回复我,谢谢。"FileInputStream问题,使用FileInputStream读取文件,并显示。文件包括两行,且都是15个字符,但结果如下。
=(-
=1-
=,-
=2-
=,-
=1-
=0-
=)-
-
=
-
=(-
=1-
=,-
=4-
=,-
=5-
=)-
17
我不知道为什么显示''=-="(11-13行的结果),长度应该是15,为什么是17?
//Code and Txt
一、ReadFile.java如下图所示。
package cn.bin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class BestWayMP {
private static final String FilePath="bestWayMP.txt";
/**
* 读取文件内容
* @return 拼接的字符串
* @throws IOException IO异常
*/
public String LoadingFiles() throws IOException {
File file=new File(FilePath);
StringBuffer buf=new StringBuffer();
if(file!=null&&file.isFile()){
FileInputStream fileInputStream=null;
fileInputStream=new FileInputStream(file);
byte r[]=new byte[1024];
int len;
while((len=fileInputStream.read(r))!=-1){
String str=new String(r,0,len,"utf-8");
buf.append(str.trim());
}
}else{
System.out.println("文件不存在");
}
return buf.toString();
}
public static void main(String args[]){
try {
String str=new BestWayMP().LoadingFiles();
for(int x=0;x<str.length();x++){
System.out.println("="+str.charAt(x)+"-");
}
System.out.println(str.length());
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、bestWayMP.txt的内容如下(编码为utf-8):。
(1,2,10)
(1,4,5)
你的文本文件有一个分行符,这个分行符被解析后添加到你的StringBuffer中,并在你的主函数中和其他字符一样被处理。当你把你的文件读到程序中时,你会得到以下信息
buf = (1,2,10)\r\n(1,4,5)
.
你可以在你的文本文件中没有行分隔符,或者你可以防止它被添加到你的StringBuffer中。
看看这个 文章 来看看如何处理它们