前言:通过文件夹中的文件的变动来随时更新数据库,更完后马上删除文件(随时删除是为了防止文件过多堆积)
项目使用maven。
步骤
1:首先通过监听器监听文件的变化
2:又新增文件就把新增文件读取出来
3:将读取出来的内容通过post请求发送给后台的接口
4:删除已读的文件
//监听文件,处理新闻
public class FileAlterationListen extends FileAlterationListenerAdaptor {
private static final String BASE_DIR = "F:\\薪资\\json";
public static String Reportname = "gsqxjb_risk_zyt_road";
public static String FileLocaltion = File.separator+"static"+File.separator+"pdf"+File.separator;
public File DirContext;
public FileAlterationListen(File dirContext) {
super();
DirContext = dirContext;
}
//文件夹创建
@Override
public void onDirectoryCreate(File directory) {
System.out.println(directory.getName()+" | 文件夹被创建"+" | 路径为:"+directory.getPath());
}
//文件夹改变
@Override
public void onDirectoryChange(File directory) {
System.out.println(directory.getName()+" | 文件夹被改变"+" | 路径为:"+directory.getPath());
}
//文件夹删除
@Override
public void onDirectoryDelete(File directory) {
System.out.println(directory.getName()+" | 文件夹被删除"+" | 路径为:"+directory.getPath());
}
//文件创建
@Override
public void onFileCreate(File file){
super.onFileCreate(file);
System.out.println(file.getName() +" | 文件被创建"+" | 路径为:"+file.getPath());
//traverseFolder(DirContext.getPath(),file.getName());
if (send(file)){
file.delete();
}else{
throw new NumberFormatException();
}
}
//文件夹改变
@Override
public void onFileChange(File file) {
super.onFileChange(file);
System.out.println(file.getName() +" | 文件被修改"+" | 路径为:"+file.getPath());
// traverseFolder(DirContext.getPath(),file.getName());
}
//文件删除
@Override
public void onFileDelete(File file) {
super.onFileDelete(file);
System.out.println(file.getName()+" | 文件被删除"+" 路径为:"+file.getPath());
// traverseFolder(DirContext.getPath(),file.getName());
}
public void traverseFolder(String path,String fileName) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
traverseFolder(file2.getAbsolutePath(),fileName);
} else {
if (fileName.equals(file2.getName())&&file2.getName().contains(Reportname)&&file2.getName().contains(".doc")) {
String name = file2.getName().substring(0, file2.getName().length()-4);
// 得到静态资源的相对地址
String Apath = FileAlterationListen.class.getClassLoader().getResource("").getPath().split("WEB-INF")[0].replaceAll("/", "\\\\"),subPath=Apath.substring(1, Apath.length());
File outFile = new File(subPath+FileLocaltion+name+".json");
// WordToPdf(file2, outFile);
}
}
}
}
} else {
System.out.println("文件不存在!");
}
}
public static void main(String[] args) {
FileAlterationMonitor monitor = new FileAlterationMonitor();
IOFileFilter filter = FileFilterUtils.or(FileFilterUtils.directoryFileFilter(),FileFilterUtils.fileFileFilter());
FileAlterationObserver observer = new FileAlterationObserver(BASE_DIR,filter);
observer.addListener(new FileAlterationListen(new File(BASE_DIR)));
monitor.addObserver(observer);
try {
//开始监听
System.out.println("文件监听……");
monitor.start();
test();
deletefile("F:\\薪资\\json");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean send(File file) {
// String path ="F:\\薪资\\json\\";
// File file = new File(path);
// File[] files = file.listFiles();
//
// for (File f:files){
// readJsonFile(BASE_DIR+f.getName());
// }
readJsonFile2(file);
return true;
}
//读取json文件
public static String readJsonFile2(File jsonFile) {
String jsonStr = "";
try {
//File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
System.out.println(jsonStr);
if (jsonStr!=null||jsonStr.length()>0){
doHttpPost2(jsonStr,"http://10.10.10.115:8084/pccareer_manager_web/newsInfo/addNews");
}
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 发送Http post请求
*
* @param xmlInfo
* json转化成的字符串
* @param URL
* 请求url
* @return 返回信息
*/
public static void doHttpPost2(String xmlInfo, String URL) {
System.out.println("发起的数据:" + xmlInfo);
byte[] xmlData = xmlInfo.getBytes();
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
java.net.URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("content-Type", "application/json");
urlCon.setRequestProperty("charset", "utf-8");
//urlCon.setRequestProperty("Content-length",
// String.valueOf(xmlData.length));
System.out.println(String.valueOf(xmlData.length));
DataOutputStream printout = new DataOutputStream(
urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
instr = urlCon.getInputStream();
byte[] bis = IOUtils.toByteArray(instr);
String ResponseString = new String(bis, "UTF-8");
if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
System.out.println("返回空");
}
// System.out.println("返回数据为:" + ResponseString);
// return ResponseString;
} catch (Exception e) {
e.printStackTrace();
// return "0";
} finally {
try {
out.close();
instr.close();
} catch (Exception ex) {
// return "0";
}
}
}
public static boolean deletefile(String delpath){
File file = new File(delpath);
if (!file.isDirectory()) {
// System.out.println("1");
file.delete();
} else if (file.isDirectory()) {
// System.out.println("2");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
// System.out.println("path=" + delfile.getPath());
// System.out.println("absolutepath="
// + delfile.getAbsolutePath());
System.out.println("name=" + delfile.getName());
delfile.delete();
// System.out.println("删除文件成功");
} else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
// 删除当前文件夹
// file.delete();
}
return true;
}
public static void test(){
String path ="F:\\薪资\\json\\";
File file = new File(path);
File[] files = file.listFiles();
for (File f:files){
readJsonFile(path+f.getName());
}
}
//读取json文件
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
System.out.println(jsonStr);
if (jsonStr!=null||jsonStr.length()>0){
doHttpPost(jsonStr,"http://10.10.10.115:8084/pccareer_manager_web/newsInfo/addNews");
}
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 发送Http post请求
*
* @param xmlInfo
* json转化成的字符串
* @param URL
* 请求url
* @return 返回信息
*/
public static void doHttpPost(String xmlInfo, String URL) {
System.out.println("发起的数据:" + xmlInfo);
byte[] xmlData = xmlInfo.getBytes();
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
java.net.URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("content-Type", "application/json");
urlCon.setRequestProperty("charset", "utf-8");
//urlCon.setRequestProperty("Content-length",
// String.valueOf(xmlData.length));
System.out.println(String.valueOf(xmlData.length));
DataOutputStream printout = new DataOutputStream(
urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
instr = urlCon.getInputStream();
byte[] bis = IOUtils.toByteArray(instr);
String ResponseString = new String(bis, "UTF-8");
if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
System.out.println("返回空");
}
// System.out.println("返回数据为:" + ResponseString);
// return ResponseString;
} catch (Exception e) {
e.printStackTrace();
// return "0";
} finally {
try {
out.close();
instr.close();
} catch (Exception ex) {
// return "0";
}
}
}
}
";
public static String Reportname = "gsqxjb_risk_zyt_road";
public static String FileLocaltion = File.separator+"static"+File.separator+"pdf"+File.separator;
public File DirContext;
public FileAlterationListen(File dirContext) {
super();
DirContext = dirContext;
}
//文件夹创建
@Override
public void onDirectoryCreate(File directory) {
System.out.println(directory.getName()+" | 文件夹被创建"+" | 路径为:"+directory.getPath());
}
//文件夹改变
@Override
public void onDirectoryChange(File directory) {
System.out.println(directory.getName()+" | 文件夹被改变"+" | 路径为:"+directory.getPath());
}
//文件夹删除
@Override
public void onDirectoryDelete(File directory) {
System.out.println(directory.getName()+" | 文件夹被删除"+" | 路径为:"+directory.getPath());
}
//文件创建
@Override
public void onFileCreate(File file){
super.onFileCreate(file);
System.out.println(file.getName() +" | 文件被创建"+" | 路径为:"+file.getPath());
//traverseFolder(DirContext.getPath(),file.getName());
if (send(file)){
file.delete();
}else{
throw new NumberFormatException();
}
}
//文件夹改变
@Override
public void onFileChange(File file) {
super.onFileChange(file);
System.out.println(file.getName() +" | 文件被修改"+" | 路径为:"+file.getPath());
// traverseFolder(DirContext.getPath(),file.getName());
}
//文件删除
@Override
public void onFileDelete(File file) {
super.onFileDelete(file);
System.out.println(file.getName()+" | 文件被删除"+" 路径为:"+file.getPath());
// traverseFolder(DirContext.getPath(),file.getName());
}
public void traverseFolder(String path,String fileName) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
traverseFolder(file2.getAbsolutePath(),fileName);
} else {
if (fileName.equals(file2.getName())&&file2.getName().contains(Reportname)&&file2.getName().contains(".doc")) {
String name = file2.getName().substring(0, file2.getName().length()-4);
// 得到静态资源的相对地址
String Apath = FileAlterationListen.class.getClassLoader().getResource("").getPath().split("WEB-INF")[0].replaceAll("/", "\\\\"),subPath=Apath.substring(1, Apath.length());
File outFile = new File(subPath+FileLocaltion+name+".json");
// WordToPdf(file2, outFile);
}
}
}
}
} else {
System.out.println("文件不存在!");
}
}
public static void main(String[] args) {
FileAlterationMonitor monitor = new FileAlterationMonitor();
IOFileFilter filter = FileFilterUtils.or(FileFilterUtils.directoryFileFilter(),FileFilterUtils.fileFileFilter());
FileAlterationObserver observer = new FileAlterationObserver(BASE_DIR,filter);
observer.addListener(new FileAlterationListen(new File(BASE_DIR)));
monitor.addObserver(observer);
try {
//开始监听
System.out.println("文件监听……");
monitor.start();
test();
deletefile("F:\\薪资\\json");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean send(File file) {
// String path ="F:\\薪资\\json\\";
// File file = new File(path);
// File[] files = file.listFiles();
//
// for (File f:files){
// readJsonFile(BASE_DIR+f.getName());
// }
readJsonFile2(file);
return true;
}
//读取json文件
public static String readJsonFile2(File jsonFile) {
String jsonStr = "";
try {
//File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
System.out.println(jsonStr);
if (jsonStr!=null||jsonStr.length()>0){
doHttpPost2(jsonStr,"http://10.10.10.115:8084/pccareer_manager_web/newsInfo/addNews");
}
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 发送Http post请求
*
* @param xmlInfo
* json转化成的字符串
* @param URL
* 请求url
* @return 返回信息
*/
public static void doHttpPost2(String xmlInfo, String URL) {
System.out.println("发起的数据:" + xmlInfo);
byte[] xmlData = xmlInfo.getBytes();
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
java.net.URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("content-Type", "application/json");
urlCon.setRequestProperty("charset", "utf-8");
//urlCon.setRequestProperty("Content-length",
// String.valueOf(xmlData.length));
System.out.println(String.valueOf(xmlData.length));
DataOutputStream printout = new DataOutputStream(
urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
instr = urlCon.getInputStream();
byte[] bis = IOUtils.toByteArray(instr);
String ResponseString = new String(bis, "UTF-8");
if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
System.out.println("返回空");
}
// System.out.println("返回数据为:" + ResponseString);
// return ResponseString;
} catch (Exception e) {
e.printStackTrace();
// return "0";
} finally {
try {
out.close();
instr.close();
} catch (Exception ex) {
// return "0";
}
}
}
public static boolean deletefile(String delpath){
File file = new File(delpath);
if (!file.isDirectory()) {
// System.out.println("1");
file.delete();
} else if (file.isDirectory()) {
// System.out.println("2");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
// System.out.println("path=" + delfile.getPath());
// System.out.println("absolutepath="
// + delfile.getAbsolutePath());
System.out.println("name=" + delfile.getName());
delfile.delete();
// System.out.println("删除文件成功");
} else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
// 删除当前文件夹
// file.delete();
}
return true;
}
public static void test(){
String path ="F:\\薪资\\json\\";
File file = new File(path);
File[] files = file.listFiles();
for (File f:files){
readJsonFile(path+f.getName());
}
}
//读取json文件
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
System.out.println(jsonStr);
if (jsonStr!=null||jsonStr.length()>0){
doHttpPost(jsonStr,"http://10.10.10.115:8084/pccareer_manager_web/newsInfo/addNews");
}
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 发送Http post请求
*
* @param xmlInfo
* json转化成的字符串
* @param URL
* 请求url
* @return 返回信息
*/
public static void doHttpPost(String xmlInfo, String URL) {
System.out.println("发起的数据:" + xmlInfo);
byte[] xmlData = xmlInfo.getBytes();
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
java.net.URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("content-Type", "application/json");
urlCon.setRequestProperty("charset", "utf-8");
//urlCon.setRequestProperty("Content-length",
// String.valueOf(xmlData.length));
System.out.println(String.valueOf(xmlData.length));
DataOutputStream printout = new DataOutputStream(
urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
instr = urlCon.getInputStream();
byte[] bis = IOUtils.toByteArray(instr);
String ResponseString = new String(bis, "UTF-8");
if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
System.out.println("返回空");
}
// System.out.println("返回数据为:" + ResponseString);
// return ResponseString;
} catch (Exception e) {
e.printStackTrace();
// return "0";
} finally {
try {
out.close();
instr.close();
} catch (Exception ex) {
// return "0";
}
}
}
}