您的位置:首页 > 数据库

从文件夹中读取txt文件 并从中截取指定的字段 内容(包括存入数据库乱码问题)

2019-03-06 20:41 363 查看

1.首先确定 从文本到程序 不是乱码(通过设定程序读取的编码格式,或者另存文件的编码格式)

/**
  * 查找文件夹下所有符合txt的文件
  *
  * @param dir 要查找的文件夹对象
  * */
public  void findFile(File dir) throws Exception {

File[] dirFiles = dir.listFiles();
Map<String,ArrayList<String>> typemap=getTypeList(new File(typeResource));//初始化  事件种类
for(File temp : dirFiles){
if(!temp.isFile()){
findFile(temp);
}
//查找指定的文件
if(temp.isFile() && temp.getAbsolutePath().endsWith(".txt") ){
//System.out.println(temp.isFile() + ":" +temp.getName()+":"+ temp.getAbsolutePath());
String txtName=temp.getName().substring(0,temp.getName().indexOf("."));//得到文件名字
           String content=getText(temp);//取得文档的内容
String  strgetString(temp,"hello");//取"hello"后面的字符串
ArrayList arr=getArrList(temp);//将文本内容按“,” 结成字符串数组
}
}
}

 

public  String getText(File file) throws Exception {
InputStreamReader isr= new InputStreamReader(new FileInputStream(file),"GBK");//这里设置编码方式,要和文档的编码相同。
BufferedReader br = new BufferedReader(isr);
String temp = null;
String contentLine ;
while ((contentLine = br.readLine()) != null) {
//            contentLine = br.readLine();
//读取每一行,并输出
// System.out.println(contentLine);
//将每一行追加到arr1
temp+=contentLine;
}
return temp;
}

 

 

public String getString(File file,String value) throws Exception {//得到特定文档内容,value是特定字符串之前的字符
String content=getText(file);
int  strBegin=content.indexOf(value)+value.length();
int  strEnd=content.indexOf("--",sumBegin);//"--"是指定字符串后面的结束字段
String string=content.substring(sumBegin,sumEnd);
return  string;
}

public ArrayList<String> getArrList(File file) throws Exception {
ArrayList<String> arrayList=new ArrayList();
String content=getText(file);
if (content!=null) {
String[] arr=content.split(",");//可以将文档内容按特定的字符划分成 字符串数组
for (int i = 1; i < arr.length; i++) {//第一个有可能不是你想要的数据,具体情况自己分析啊
arrayList.add(arr[i].substring(0, arr[i].indexOf(";")));
}
}
return  arrayList;
}

 

findFile(new File(basePath));这么调用

 

2.确定程序写入到数据库不是乱码。

2.1通过数据库连接字符串修改写入的编码格式。

[code]<property name="url" value="jdbc:mysql://192.168.0.0:3306/aaa?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;useOldAliasMetadataBehavior=true&amp;autoReconnect:true "/>

2.2 修改数据库的编码(一般不修改数据库的编码)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: