您好,我是一名中国计算机专业的研究生,我有一个简单的问题不知道为什么,请回复我,谢谢。 FileInputStream 问题,使用FileInputStream读取文件,并显示。 txt包含两行,均为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 中。
看看这个 article看看如何处理它们
关于Java FileInputStream读取字符不准确????,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62041337/