1. 程式人生 > 其它 >讀取路徑下檔案內容並存放資料庫

讀取路徑下檔案內容並存放資料庫

讀取路徑下檔案內容並放在資料庫中

import org.springframework.jdbc.core.JdbcTemplate;

import java.io.*;
import java.util.HashMap;

public class PathReaderTest {

    public static void main(String[] args) {

    }
//從路徑下解析檔案,判斷是否為路徑
    public static void readfile(String filePath) throws IOException {
        try{
        File file 
= new File(filePath); // isDirectory判斷是否是一個路徑 if(!file.isDirectory()){ System.out.println("路徑下是一個檔案"); System.out.println("path="+file.getPath()); System.out.println("absolutepath="+file.getAbsolutePath()); System.out.println("name="+file.getName()); readContent(filePath); }
else if(file.isDirectory()){ System.out.println("這個路徑下是一個資料夾"); String[] fileList = file.list(); for(int i=0;i<fileList.length;i++){ //如果是一個資料夾,則一直往下讀取,直到是檔案了為止 filePath = filePath+"\\"+fileList[i]; readfile(filePath); } } }
catch(FileNotFoundException){ System.out.println("read e:"); } return ; } public static void readContent(String filepath) throws IOException { Reader f1 = new FileReader(filepath); BufferedReader file = new BufferedReader(f1); HashMap<String,String> result = new HashMap<String,String>(); String line=""; while((line=file.readLine())!=null){ String id = line.split("\\W+")[0]; result.put("id",id); String name = line.split("\\W+")[1]; result.put("name",name); String age = line.split("\\W+")[2]; result.put("age",age); int up = writeDB(result); }} public int writeDB(HashMap<String,String> result){ String id = result.get(id); String name =result.get(name); String age = result.get(age); String sql = "INSERT INTO table_name VALUES(?,?,?)"; int dbresult = JdbcTemplate.update(sql,new Object[]{id,name,age}); return dbresult; } }