原本的代碼中是這樣的:
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;
}