读取路径下文件内容并存放数据库
读取路径下文件内容并放在数据库中
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; } }