原方法
public static void loadFile(){
try {
File file = new File("Account/userAccount.txt");
if(!file.exists()){
System.out.println("文件不存在!");
}
BufferedReader br = new BufferedReader(new FileReader(file));//缓冲字节流读取文件账户密码
String s = null;
while((s = br.readLine())!=null){//每行读取账户密码
String[] splits=s.split("\\s");
Util.map.put(splits[0], splits[1]);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
换成字节流读取之后方法:
public static void loadFile(){
try {
Resource resource = new ClassPathResource("Account/userAccount.txt");
InputStream inputStream = resource.getInputStream();
if(!resource.exists()){
System.out.println("文件不存在!");
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(bufferedInputStream,StandardCharsets.UTF_8));
String s = null;
while((s = bufferreader.readLine())!=null){//每行读取账户密码
String[] splits=s.split("\\s");
Util.map.put(splits[0], splits[1]);
}
bufferreader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
关键代码:
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(bufferedInputStream,StandardCharsets.UTF_8));
注意:根据文件编码选择正确的编码格式。