java常用工具方法
1、两个数相除,保留两位小数
public static void main(String[] args) {
double divide = divide(1, 3, 2);
System.out.println(divide);//0.33
System.out.println(divide * 100 + "%");//33.0%
}
public static double divide(double a, double b, int scale) {
BigDecimal bd1 = new BigDecimal(Double.toString(a));
BigDecimal bd2 = new BigDecimal(Double.toString(b));
return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
2、文件转字节数组,字节数组转文件
应用场景: 需要像第三方系统传数据,并且以json格式传。记得中间要用base64把字节转成一个编码串。
public static void main(String[] args) {
byte[] bytesByFile = getBytesByFile("D:\\aa.txt");
//对字节数组进行base64编码
String encoded = Base64.getEncoder().encodeToString(bytesByFile);
System.out.println(encoded);
//把base64编码转成字节
byte[] decoded = Base64.getDecoder().decode(encoded);
getFileByBytes(decoded,"D:\\","bb.txt");
}
/**
* 将文件转换成Byte数组
* @param pathStr
* @return
*/
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将Byte数组转换成文件
* @param bytes
* @param filePath
* @param fileName
*/
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}