原本的代码中是这样的:
String path = args[0];
File file = new File(path);
StringBuilder sb = new StringBuilder();
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
while ( fileInputStream.read(bytes) > 0) {
sb.append(new String(bytes));
}
} catch (IOException e) {
System.out.println("文件读取异常");
return;
}
这个会有什么问题呢?假如文件最后一次读取长度不足1024,会在字符串的最后面拼空格。
改吧改吧:记录读到的长度,拼到后面
String path = args[0];
File file = new File(path);
StringBuilder sb = new StringBuilder();
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int count = 0;
while ((count = fileInputStream.read(bytes)) > 0) {
sb.append(new String(bytes, 0, count));
}
} catch (IOException e) {
System.out.println("文件读取异常");
return;
}