一、讀取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;
}
}