您的位置:首页 > 编程语言

创新实训——工具类:代码优化

2018-08-28 13:39 162 查看

1.简介  

合理地将重复使用的方法抽离出来,并放到工具类里会有效的优化代码结构,使代码更简洁。

2.一些工具类和常用的方法

[code]public class ToolUtil {
//关闭继承自AutoCloseable的流
public static void closeQuietly(@NotNull AutoCloseable... closeable) {
for (int i = 0; i < closeable.length; i++) {
try {
closeable.clone();
} catch (Exception e) {
//ignore
}
}
}
//将字符串写入到response中
public static void responseJson(HttpServletResponse response, String str) {
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(str);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
//设置request和response的编码,避免出现中文乱码
public static void setEncode(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
[code]public class CmdUtil {
//执行linux命令行
public static boolean exec(String cmd) {
try {
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd}).destroy();
return true;
} catch (IOException e) {
return false;
}
}
//执行linux命令行,并返回输出结果
public static List<String> execWithOutput(String cmd) {
List<String> list = null;
try {
Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
list = new ArrayList<>();
String result;
while ((result = bs.readLine()) != null) {
list.add(result);
}
in.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
} finally {
return list;
}
}
}
[code]public class ImageUtil {

/**
* 上传文件到七牛云服务器
*
* @param imgPath 图片的存储路径
* @return 图片的url
*/
public static String uploadImage(String imgPath) {
Auth auth = Auth.create(BaseConsts.ACCESS_KEY, BaseConsts.SECRET_KEY);
String token = auth.uploadToken(BaseConsts.BUCKET);

Configuration configuration = new Configuration(Zone.autoZone());
UploadManager manager = new UploadManager(configuration);
try {
Response response = manager.put(imgPath, null, token);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return BaseConsts.BASE_IMG_URL + putRet.hash;
} catch (QiniuException e) {
e.printStackTrace();
}
return null;
}

/**
* 下载图片
*
* @param url     图片的url
* @param imgPath 指定图片的存储路径
*/
public static void downloadImage(String url, String imgPath) {
try {
URL url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(imgPath);
byte[] bytes = new byte[1024 * 128];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
}
System.out.println("responseCode is "+responseCode+"\n"
+"url is "+url);
} catch (Exception e) {
e.printStackTrace();
}finally {

}
}
}

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: