一、读取json文件
直接读取文件,并转化为map
ObjectMapper objectMapper = new ObjectMapper();
try {
Map map = objectMapper.readValue(new File(filePath), Map.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
二、读取普通文件
使用FileInputStream效率最高!
下面是每次读取1024个字节
public static String readFile(String filePath) {
StringBuffer stringBuffer = new StringBuffer("");
byte[] buffer = new byte[1024];
int count = 0;
File file = new File(filePath);
try {
InputStream inputStream = new FileInputStream(file);
while (-1 != (count = inputStream.read(buffer))) {
stringBuffer.append(new String(buffer, 0, count));
}
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return stringBuffer.toString();
}
下面是读取所有字节
public static String readFile(String filePath) {
String encoding = "UTF-8";
File file = new File(filePath);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return null;
}
}
前方一片光明 发布了112 篇原创文章 · 获赞 1583 · 访问量 46万+ 关注