目录
Java开发常用工具类
1: Http工具类
2: Java8时间转换常用工具类
3: Java统计List集合中每个元素出现的次数
4: 生成指定范围,指定小数位数的随机数
5: 获取Linux系统IP地址相关
6: 操作Ftp相关
7: 操作Csv工具类
8: PDF && BASE64互转
package com.sun.collierycommon.utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @Author: wcybaonier
*/
public class SmartHttpUtil {
/**
* 方法描述: 发送get请求
*
* @param url
* @param params
* @param header
* @Return {@link String}
* @throws
*/
public static String sendGet(String url, Map params, Map header) throws Exception {
HttpGet httpGet = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
List mapList = new ArrayList<>();
if (params != null) {
for (Entry entry : params.entrySet()) {
mapList.add(entry.getKey() + "=" + entry.getValue());
}
}
if (CollectionUtils.isNotEmpty(mapList)) {
url = url + "?";
String paramsStr = StringUtils.join(mapList, "&");
url = url + paramsStr;
}
httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json; charset=utf-8");
httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpGet != null) {
httpGet.releaseConnection();
}
}
return body;
}
/**
* 方法描述: 发送post请求-json数据
*
* @param url
* @param json
* @param header
* @Return {@link String}
* @throws
*/
public static String sendPostJson(String url, String json, Map header) throws Exception {
HttpPost httpPost = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
StringEntity entity = new StringEntity(json, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return body;
}
/**
* 方法描述: 发送post请求-form表单数据
*
* @param url
* @param json
* @param header
* @Return {@link String}
* @throws
*/
public static String sendPostForm(String url, Map params, Map header) throws Exception {
HttpPost httpPost = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
List nvps = new ArrayList<>();
if (params != null) {
for (Entry entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return body;
}
}
苦于各种时间转换工具包转换的时间千奇百怪,各种BUG, 自己整理了一份基于JDK8的工具类,真实项目中测试OK, 欢迎各位提出宝贵意见!
package com.idc.utils;
import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class LocalDateUtil {
/**
* 日期格式yyyy-MM-dd
*/
public static String DATE_PATTERN = "yyyy-MM-dd";
/**
* 日期格式yyyy年dd月
*/
public static String DATE_PATTERN2 = "yyyy年MM月";
/**
* 日期格式yyyy年dd月
*/
public static String DATE_PATTERN3 = "yyyy-MM";
/**
* 日期时间格式yyyy-MM-dd HH:mm:ss
*/
public static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 时间格式yyyy-MM-dd HH:mm:ss
*/
public static String TIME_PATTERN = "HH:mm:ss";
/**
* 获取默认时间格式: yyyy-MM-dd HH:mm:ss
*/
public static DateTimeFormatter DEFAULT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss+08:00");
public static DateTimeFormatter DEFAULT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 构造函数
*/
private LocalDateUtil() {
super();
}
/**
* Date转LocalDateTime
*
* @param date Date对象
* @return
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
/**
* LocalDateTime转换为Date
*
* @param dateTime LocalDateTime对象
* @return
*/
public static Date localDateTimeToDate(LocalDateTime dateTime) {
return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 格式化时间-默认yyyy-MM-dd HH:mm:ss格式
*
* @param dateTime LocalDateTime对象
* @return
*/
public static String formatLocalDateTime(LocalDateTime dateTime) {
return formatLocalDateTime(dateTime, DATE_TIME_PATTERN);
}
/**
* 格式化时间为字符串-默认yyyy-MM-dd 格式
*
* @param date LocalDate对象
* @return
*/
public static String formatLocalDateToStr(LocalDate date, String pattern) {
if (date == null) {
return "";
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return date.format(formatter);
}
/**
* String 转时间-默认yyyy-MM-dd格式
*
* @param timeStr 字符串
* @return
*/
public static LocalDate parseStrToLocalDate(String timeStr) {
if (timeStr == null || timeStr.isEmpty()) {
return null;
}
return LocalDate.parse(timeStr, DEFAULT_DATE_FORMATTER);
}
/**
* LocalDateTime
*
* @param localDateTime
* @return yyyy-MM-dd
*/
public static String parseLocalDateTimeToString(LocalDateTime localDateTime) {
return localDateTime.format(DEFAULT_DATETIME_FORMATTER);
}
/**
* 按pattern格式化时间-默认yyyy-MM-dd HH:mm:ss格式
*
* @param dateTime LocalDateTime对象
* @param pattern 要格式化的字符串
* @return
*/
public static String formatLocalDateTime(LocalDateTime dateTime, String pattern) {
if (dateTime == null) {
return "";
}
if (pattern == null || pattern.isEmpty()) {
pattern = DATE_TIME_PATTERN;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return dateTime.format(formatter);
}
/**
* String 转时间-默认yyyy-MM-dd HH:mm:ss格式
*
* @param timeStr 字符串
* @return
*/
public static LocalDateTime parseStrToLocalDateTime(String timeStr) {
if (timeStr == null || timeStr.isEmpty()) {
return null;
}
return LocalDateTime.parse(timeStr, DEFAULT_DATETIME_FORMATTER);
}
/**
* 获取今天的00:00:00
*
* @return
*/
public static String getDayStart() {
return getDayStart(LocalDateTime.now());
}
/**
* 获取今天的23:59:59
*
* @return
*/
public static String getDayEnd() {
return getDayEnd(LocalDateTime.now());
}
/**
* 获取某天的00:00:00
*
* @param dateTime
* @return
*/
public static String getDayStart(LocalDateTime dateTime) {
return formatLocalDateTime(dateTime.with(LocalTime.MIN));
}
/**
* 获取某天的23:59:59
*
* @param dateTime
* @return
*/
public static String getDayEnd(LocalDateTime dateTime) {
return formatLocalDateTime(dateTime.with(LocalTime.MAX));
}
/**
* 获取本月第一天的00:00:00
*
* @return
*/
public static String getFirstDayOfMonth() {
return getFirstDayOfMonth(LocalDateTime.now());
}
/**
* 获取本月最后一天的23:59:59
*
* @return
*/
public static String getLastDayOfMonth() {
return getLastDayOfMonth(LocalDateTime.now());
}
/**
* 获取某月第一天的00:00:00
*
* @param dateTime LocalDateTime对象
* @return
*/
public static String getFirstDayOfMonth(LocalDateTime dateTime) {
return formatLocalDateTime(dateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN));
}
/**
* 获取某月最后一天的23:59:59
*
* @param dateTime LocalDateTime对象
* @return
*/
public static String getLastDayOfMonth(LocalDateTime dateTime) {
return formatLocalDateTime(dateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX));
}
@SneakyThrows
public static Date strToDate(String time) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.parse(time);
}
/**
* 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss
*/
public static String timeToString(Long time){
Assert.notNull(time, "time is null");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
}
/**
* 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss
*/
public static Long timeToLong(String time) {
Assert.notNull(time, "time is null");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse("2019-11-28 08:52:50", ftf);
return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
/**
* 计算 两个时间相差的季度数
* @param startDate 2017-02-31
* @param endDate 2017-03-01
* @return
*/
public static int differQuarter(String startDate,String endDate){
int a =0;
String[] ss= startDate.split("-");
String[] ee= endDate.split("-");
String sy =ss[0];
String sm=ss[1];
String ey=ee[0];
String em = ee[1];
int syi=Integer.parseInt(sy);
int smi=Integer.parseInt(sm);
int eyi=Integer.parseInt(ey);
int emi=Integer.parseInt(em);
a= ((eyi-syi)*12 +(emi-1))/3-(smi-1)/3+1;
return a;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
/*System.out.println(getDayStart());
System.out.println(getDayEnd());
System.out.println(getFirstDayOfMonth());
System.out.println(getLastDayOfMonth());
System.out.println(LocalDateUtil.formatDateTime(LocalDateTime.now(), LocalDateUtil.TIME_PATTERN));
System.out.println(parseStrToLocalDateTime("2018-12-12 10:10:10"));*/
System.out.println(formatLocalDateToStr(LocalDate.now(), DATE_PATTERN3));
/*System.out.println(parseStrToLocalDate("2019-12-12"));
System.out.println(LocalDate.now().toString().substring(0, 7));*/
}
public static String StringsecondToTime(long second) {
long days = second / 86400;//转换天数
second = second % 86400;//剩余秒数
long hours = second / 3600;//转换小时数
second = second % 3600;//剩余秒数
long minutes = second / 60;//转换分钟
second = second % 60;//剩余秒数
if (0 < days) {
return days + "天" + hours + "小时" + minutes + "分钟" + second + "秒";
} else {
return hours + "小时" + minutes + "分钟" + second + "秒";
}
}
}
java 8 Localdate常用API:
====================================正确答案==================================
getYear() int 获取当前日期的年份
getMonth() Month 获取当前日期的月份对象
getMonthValue() int 获取当前日期是第几月
getDayOfWeek() DayOfWeek 表示该对象表示的日期是星期几
getDayOfMonth() int 表示该对象表示的日期是这个月第几天
getDayOfYear() int 表示该对象表示的日期是今年第几天
withYear(int year) LocalDate 修改当前对象的年份
withMonth(int month) LocalDate 修改当前对象的月份
withDayOfMonth(int dayOfMonth) LocalDate 修改当前对象在当月的日期
isLeapYear() boolean 是否是闰年
lengthOfMonth() int 这个月有多少天
lengthOfYear() int 该对象表示的年份有多少天(365或者366)
plusYears(long yearsToAdd) LocalDate 当前对象增加指定的年份数
plusMonths(long monthsToAdd) LocalDate 当前对象增加指定的月份数
plusWeeks(long weeksToAdd) LocalDate 当前对象增加指定的周数
plusDays(long daysToAdd) LocalDate 当前对象增加指定的天数
minusYears(long yearsToSubtract) LocalDate 当前对象减去指定的年数
minusMonths(long monthsToSubtract) LocalDate 当前对象减去注定的月数
minusWeeks(long weeksToSubtract) LocalDate 当前对象减去指定的周数
minusDays(long daysToSubtract) LocalDate 当前对象减去指定的天数
compareTo(ChronoLocalDate other) int 比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚,
isBefore(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之前
isAfter(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之后
isEqual(ChronoLocalDate other) boolean 比较两个日期对象是否相等
/**
* java统计List集合中每个元素出现的次数
* 例如frequencyOfListElements(["111","111","222"])
* ->
* 则返回Map {"111"=2,"222"=1}
* @param items
* @return Map
* @author wuqx
*/
public static Map frequencyOfListElements( List items ) {
if (items == null || items.size() == 0) return null;
Map map = new HashMap();
for (String temp : items) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
return map;
/**
* 生成指定范围,指定小数位数的随机数
* @param max 最大值
* @param min 最小值
* @param scale 小数位数
* @return
*/
public static BigDecimal makeRandom(float max,float min,int scale){
BigDecimal cha = new BigDecimal(Math.random() * (max-min) + min);
return cha.setScale(scale,BigDecimal.ROUND_HALF_UP);//保留 scale 位小数,并四舍五入
}
/**
* 获取本地IP地址
*
* @throws SocketException
*/
public static String getLocalIP() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLinuxLocalIp();
}
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取本地Host名称
*/
public static String getLocalHostName() throws UnknownHostException {
return InetAddress.getLocalHost().getHostName();
}
/**
* 获取Linux下的IP地址
*
* @return IP地址
* @throws SocketException
*/
private static String getLinuxLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
System.out.println(ipaddress);
}
}
}
}
}
} catch (SocketException ex) {
System.out.println("获取ip地址异常");
ip = "127.0.0.1";
ex.printStackTrace();
}
System.out.println("IP:"+ip);
return ip;
}
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
*
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
*
* 用户真实IP为: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.SocketException;
public class FTPUtil {
/**
* 打开FTP服务链接
* @param ftpHost
* @param ftpPort
* @param ftpUserName
* @param ftpPassword
*/
public static FTPClient getFTPClient(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword){
FTPClient ftpClient = null;
try {
ftpClient = new FTPClient();
ftpClient.setConnectTimeout(60000);
if(ftpPort != null){
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
}else {
ftpClient.connect(ftpHost);// 连接FTP服务器
}
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(ftpUserName, ftpPassword)) {// 登陆FTP服务器
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
"OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
ftpClient.setControlEncoding("UTF-8");
}else {
ftpClient.setControlEncoding("GBK");
}
ftpClient.enterLocalPassiveMode();// 设置被动模式
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置传输的模式,以二进制流的方式读取
ftpClient.enterLocalPassiveMode();
System.out.println("FTP服务连接成功!");
}else {
System.out.println("FTP服务用户名或密码错误!");
disConnection(ftpClient);
}
}else {
System.out.println("连接到FTP服务失败!");
disConnection(ftpClient);
}
} catch (SocketException e) {
e.printStackTrace();
disConnection(ftpClient);
System.out.println("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
disConnection(ftpClient);
System.out.println("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/**
* 关闭FTP服务链接
* @throws IOException
*/
public static void disConnection(FTPClient ftpClient){
try {
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取文件夹下的所有文件信息
* @param path 文件路径
*/
public static FTPFile[] getFTPDirectoryFiles(FTPClient ftpClient,String path){
FTPFile[] files = null;
try {
ftpClient.changeWorkingDirectory(path);
files = ftpClient.listFiles();
}catch (Exception e){
e.printStackTrace();
//关闭连接
disConnection(ftpClient);
System.out.println("FTP读取数据异常!");
}
return files;
}
/**
* 获取文件夹下的所有文件信息
* @param path 文件路径
*/
public static InputStream getFTPFile(FTPClient ftpClient,String path,String fileName){
InputStream in = null;
try {
ftpClient.changeWorkingDirectory(path);
FTPFile[] files = ftpClient.listFiles();
if(files.length > 0){
in = ftpClient.retrieveFileStream(fileName);
}
}catch (Exception e){
e.printStackTrace();
System.out.println("FTP读取数据异常!");
}finally {
//关闭连接
disConnection(ftpClient);
}
return in;
}
/**
* 下载获取ftp上修改时间、创建时间最新的文件
* @param ftpClient
* @return
*/
public static String getNewestFileName(FTPClient ftpClient) {
//获取ftp目录下所有文件
FTPFile[] files= new FTPFile[0];
try {
files = ftpClient.listFiles();
} catch (IOException e) {
e.printStackTrace();
}
//文件放入自定义集合
List list = new ArrayList<>(Arrays.asList(files));
//根据文件修改时间获取最新的文件
list.sort((file1, newFile) -> {
if (file1.getTimestamp().compareTo(newFile.getTimestamp()) < 0) {
return 1;
} else if (file1.getTimestamp().compareTo(newFile.getTimestamp()) == 0) {
return 0;
} else {
return -1;
}
});
return list.get(0).getName();
}
public static void main(String args[]){
InputStream in = null;
BufferedReader br = null;
try{
String path = "/home/ftp/";
//读取单个文件
FTPClient ftpClient = getFTPClient("10.1.1.1",21,"username","123456");
String fileName = "person.txt";
in = getFTPFile(ftpClient,path,fileName);
if(in != null){
br = new BufferedReader(new InputStreamReader(in,"GBK"));
String data = null;
while ((data = br.readLine()) != null) {
String[] empData = data.split(";");
System.out.println(empData[0]+" "+empData[1]);
}
}
//读取文件夹下的所有文件
FTPClient ftpClient1 = getFTPClient("10.1.1.1",21,"username","123456");
FTPFile[] files = getFTPDirectoryFiles(ftpClient1,path);
if(files != null && files.length > 0){
for (int i = 0; i < files.length; i++) {
if(files[i].isFile()){
in = ftpClient1.retrieveFileStream(files[i].getName());
br = new BufferedReader(new InputStreamReader(in,"GBK"));
System.out.println(files[i].getName());
}
}
}
//关闭连接
disConnection(ftpClient1);
}catch (Exception e){
e.printStackTrace();
}finally {
try{
//关闭流
if (br != null)
br.close();
if (in != null)
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
package cn.unicom.util;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 读写csv文件工具类
*
**/
public class CsvUtil {
public static void main(String[] args) throws Exception{
File file = new File("C:\\Users\\wcy\\Desktop\\His_20211013150000.csv");
InputStream inputStream = new FileInputStream(file);
List list = read(inputStream,"GB2312");
write(list,"C:\\Users\\wcy\\Desktop\\His_202110131500001.csv");
}
/**
* 读取csv文件内容
* @param inputStream
* @param code csv文件的编码,如utf8,,gbk
*
* @return 返回csv文件中的数据
* @throws Exception
*/
public static List read(InputStream inputStream, String code) throws Exception{
//1. 存储csv文件中的内容
List csvList = new ArrayList();
//2. 创建CsvReader
CsvReader reader = new CsvReader(inputStream, ',', Charset.forName(code));
//3. 跳过表头,如果需要表头的话,不要写这句
// reader.readHeaders();
//4.逐行读入除表头的数据
while(reader.readRecord()){
csvList.add(reader.getValues());
}
//5. 释放资源
reader.close();
return csvList;
}
/**
* 数据写入csv文件
* @param list UTF-8编码写入csv文件的内容
* @param filePath 写入的csv文件的指定路劲
*
* @throws Exception
*/
public static void write(List list, String filePath) throws Exception{
CsvWriter wr = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
for (int i = 0; i < list.size(); i++) {
wr.writeRecord(list.get(i));
}
wr.close();
}
}
package cn.chinaunicom.devops.app.util;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class PDFFileUtils {
/**
* 方法名: PDFToBase64
* 方法功能描述: 将pdf文件转换为Base64编码
* @param: String sourceFile:源文件路径
* @return: String base64字符串
* @Author: zhouhu
* @Create Date: 2019年07月03日
*/
public static String PDFToBase64(String sourceFile) {
BASE64Encoder encoder = new BASE64Encoder();
FileInputStream fin =null;
BufferedInputStream bin =null;
ByteArrayOutputStream baos = null;
BufferedOutputStream bout =null;
File file = new File(sourceFile);
try {
fin = new FileInputStream(file);
bin = new BufferedInputStream(fin);
baos = new ByteArrayOutputStream();
bout = new BufferedOutputStream(baos);
byte[] buffer = new byte[1024];
int len = bin.read(buffer);
while(len != -1){
bout.write(buffer, 0, len);
len = bin.read(buffer);
}
//刷新此输出流并强制写出所有缓冲的输出字节
bout.flush();
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fin.close();
bin.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 方法名: base64StringToPDF
* 方法功能描述: 将base64编码内容转换为Pdf
* @param: String base64Str:图片的base64字符串;
* String businessType:图片数据类型
* @return: void
* @Author: zhouhu
* @Create Date: 2019年07月03日
*/
public static void base64StringToPDF(String base64Content,String realPath,String fileName){
BASE64Decoder decoder = new BASE64Decoder();
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
//1.base64编码内容转换为字节数组
byte[] bytes = decoder.decodeBuffer(base64Content);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
bis = new BufferedInputStream(byteInputStream);
//2.生成pdf
String trueFileName=fileName+".pdf";
String imageSavePath = realPath + trueFileName;
File file = new File(imageSavePath);
File path = file.getParentFile();
if(!path.exists()){
path.mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int length = bis.read(buffer);
while(length != -1){
bos.write(buffer, 0, length);
length = bis.read(buffer);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
bis.close();
fos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String s = PDFFileUtils.PDFToBase64("C:\\Users\\wcybaonier\\Desktop\\辛亥:摇晃的中国(www.pdfzj.cn) .pdf");
System.out.println(s);
PDFFileUtils.base64StringToPDF(s,"C:\\Users\\wcybaonier\\Desktop\\","111");
}
}