文章目录
- 1. 读取配置文件数据
- 2. java异常处理注意事项
1. 读取配置文件数据
配置文件:filePath.properties
sourcePath=C:\\Users\\18751\\Desktop\\ti.zip
destPath=C:\\Users\\18751\\Desktop\\ti\\
passWord=sangfor123
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyUtil {
//日志
private static Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
//创建集合(map)
private static Properties properties = new Properties();
//static修改的初始化代码块
static {
InputStream inputStream = null;
try {
// 方式1:通过当前类加载器的getResourceAsStream方法获取
// inputStream = PropertyUtil.class.getClassLoader().getResourceAsStream("filePath.properties");
// 方式2:从文件获取
inputStream = new FileInputStream(new File(System.getProperty("user.dir")+"/folder"+"/filePath.properties"));
//从输入流中读取属性列表
properties.load(inputStream);
} catch (Exception e) {
logger.error("读取配置文件失败,{}",e.toString());
}finally {
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
logger.error("流关闭失败,{}",e.toString());
}
}
}
//通过配置文件的键获取值
public static String getProperty(String key){
return properties.getProperty(key);
}
}
测试类:
public class PracticeDemo {
public static void main(String[] args) {
//解压文件
String sourcePath = PropertyUtil.getProperty("sourcePath");
String destPath = PropertyUtil.getProperty("destPath");
String passWord = PropertyUtil.getProperty("passWord");
UnZipUtil.unZip(sourcePath,destPath,passWord);
}
}
2. java异常处理注意事项
① 捕获异常,却不做处理,屏蔽了异常的所有信息,出现异常时所有人感知不到,但是该处的代码或者调用该代码的相关功能都会出现问题,在排查问题是让人无从下手,没有达到预期的效果。
try {
xxxxxx
} catch(Exception e) {
}
② 对于不用逻辑处理的异常,至少添加一个日志打印,毕竟这是一种异常场景,是有问题才会出现的场景,需要把相关日志打印出来,便于排查问题出现的原因进而修复问题,打印异常日志时一定要把异常本身的信息打印出来,不然出现异常时任然无法准确定位。
注意打印异常信息时不要使用e.printStackTrace();,建议直接使用代码日志框架,printStackTrace()默认使用了System.err输出流进行输出,与System.out是两个不同的输出流,会导致打印出的堆栈日志跟正常输出或者业务代码执行日志交错在一起,导致日志混乱影响日志分析。并且该异常还会打印到控制台,产生错误堆栈字符串到字符串池内存空间,异常信息过多就会导致内存被占满,服务异常。
错误方式:
import org.junit.Test;
import java.io.*;
public class OutputStreamDemo {
@Test
public void testBufferedWriter() {
String filePath = "E://IO//Demo//a.txt";
File file = buileFile(filePath);
String string = "jiang hui ni hao";
BufferedWriter bufferedWriter = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
OutputStreamWriter outputStreamWriter
= new OutputStreamWriter(fileOutputStream,"utf-8");
bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(string);
bufferedWriter.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bufferedWriter!=null){
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 创建一个以filePath为路径的文件对象
* @param filePath
* @return
*/
private File buileFile(String filePath) {
File file = new File(filePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}
正确方式:
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class OutputStreamDemo {
private static Logger logger = LoggerFactory.getLogger(OutputStreamDemo.class);
@Test
public void testBufferedWriter() {
String filePath = "E://IO//Demo//a.txt";
File file = buileFile(filePath);
String string = "jiang hui ni hao";
BufferedWriter bufferedWriter = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);。
OutputStreamWriter outputStreamWriter
= new OutputStreamWriter(fileOutputStream,"utf-8");
bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(string);
bufferedWriter.flush();
} catch (FileNotFoundException e) {
logger.error("json要写入的文件不存在异常,{}",e.toString());
} catch (UnsupportedEncodingException e) {
logger.error("转码异常,{}",e.toString());
} catch (IOException e) {
logger.error("json写入文件异常,{}",e.toString());
}finally {
if(bufferedWriter!=null){
try {
bufferedWriter.close();
} catch (IOException e) {
logger.error("流关闭异常,{}",e.toString());
}
}
}
}
/**
* 创建一个以filePath为路径的文件对象
* @param filePath
* @return
*/
private File buileFile(String filePath) {
File file = new File(filePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
logger.error("文件创建失败,{}",e.toString());
}
}
return file;
}
}
③ 建议不要直接捕获受检异常的基类Exception
首先,捕获异常就是为了处理异常,不同的异常需要有不同的处理方式,区分并捕获具体的异常,就可以对具体的异常做出最准确的处理,并且对应的异常信息也是最准确的,直接捕获Exception有时会导致真实出现的异常信息模糊。
错误方式:
import org.junit.Test;
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InputStreamDemo {
private static Logger logger = LoggerFactory.getLogger(InputStreamDemo.class);
/**
* 读取文件内容并拼接为字符串
* @param fullPath 文件路径
*/
@Test
public static String readJsonFile(String fullPath) {
String jsonString = "";
BufferedReader bufferedReader = null;
try {
FileInputStream fileInputStream = new FileInputStream(fullPath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line=bufferedReader.readLine())!=null){
jsonString += line;
}
//有多个异常时要分别写出,而不是直接抛出Exception
} catch (Exception e) {
logger.error("读取文件失败:{}",e.getMessage());
}finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
logger.error("IO流关闭失败:{}",e.getMessage());
}
}
}
return jsonString;
}
}
正确方式:
import org.junit.Test;
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InputStreamDemo {
private static Logger logger = LoggerFactory.getLogger(InputStreamDemo.class);
/**
* 读取文件内容并拼接为字符串
* @param fullPath 文件路径
*/
@Test
public static String readJsonFile(String fullPath) {
// 定义返回结果
String jsonString = "";
BufferedReader bufferedReader = null;
try {
FileInputStream fileInputStream = new FileInputStream(fullPath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line=bufferedReader.readLine())!=null){
jsonString += line;
}
} catch (UnsupportedEncodingException e) {
logger.error("转码异常,{}",e.toString());
} catch (FileNotFoundException e) {
logger.error("系统找不到指定路径异常,{}",e.toString());
} catch (IOException e) {
logger.error("文件读取失败异常,{}",e.toString());
}finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
logger.error("IO流关闭失败:{}",e.getMessage());
}
}
}
return jsonString;
}
}
④ RuntimeException不应该去捕获处理
RuntimeException是运行时异常,表示代码本身存在BUG,比如ArrayIndexOutOfBoundsException,数组下标越界,代码若不调BUG进行处理肯定还会报错,控制台一旦报RuntimeException,不是try-catch就能解决的。这种可控的异常场景应该在编码的时候识别出来进行处理。
错误方式:
try {
obj.method();
//不可捕获
} catch(NullPointerException e){
log.error(e,getMessage());
}
正确方式:
if (obj != null) {
obj.method();
}
⑤ 注意try-catch作用域
不是所有代码都需要进行try-catch的,不能每个方法中都直接整个try-catch,大段代码的try-catch会影响代码的可读性,也会增大异常出现的场景定位难度,catch时请分清稳定代码和非稳定代码,稳定代码指的是无论如何不会出错的代码。对于非稳定代码的catch尽可能进行区分异常类型,再做对应的异常处理。