java处理Txt文件并且存入数据库
txt文件是存储在电脑上,思路是:
先将txt按照每一行读取,将读到的文件存在list数据中。然后每次循环将list的每一个数据进行按照你的条件拆分,我是按照“,”进行拆分的。
先看一下我的txt文件:
这是拆分后的结果:
package com.mysql; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import com.service.MessageService; import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; public class testmysql { public static ArrayList<String> getfile(String filepath){ try{ String temp = null; File f = new File(filepath); //指定读取编码用于读取中文 InputStreamReader read = new InputStreamReader(new FileInputStream(f),"utf-8"); ArrayList<String> readList = new ArrayList<String>(); BufferedReader reader=new BufferedReader(read); //bufReader = new BufferedReader(new FileReader(filepath)); while((temp=reader.readLine())!=null &&!"".equals(temp)){ readList.add(temp); } read.close(); return readList; }catch (Exception e) { e.printStackTrace(); } return null; } //改变时间的格式 public static String parseDate(String dateStr) throws java.text.ParseException{ SimpleDateFormat input_date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH); SimpleDateFormat output_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String finalDate = ""; try { Date parse_date = input_date.parse(dateStr); finalDate = output_date.format(parse_date); } catch (ParseException e) { e.printStackTrace(); } return finalDate; } public static void main(String[] args) throws java.text.ParseException { //txt文件读取 ArrayList<String> list=getfile("D:\\result.txt"); //List<String> list1=new ArrayList<String>(); int num=list.size(); for (int i = 0; i < num; i++) { //System.out.println(list.get(i)); if (list.get(i)!=null) { String[] s=list.get(i).split(","); String data=parseDate(s[1]); //txt每行可以分割成6个字符串存到是s[], String sql = "insert into detailresult(ip,time,day,traffic,type,id) values('" + s[0] + "','" +data + "','" +s[2] + "','" + s[3] +"','" + s[4] +"','" + s[5] + "')"; MessageService.add(sql); } } System.out.println("添加成功"); } }