文件读写foreach|php读取txt文件 然后写入数据库

① java璁捐¢樺寘鍚闆嗗悎锛宨terator for锛宖oreach锛屾枃浠惰诲啓杩欏嚑涓鐭ヨ瘑鐐

importjava.util.*;importjava.io.*;/***@author:kaifang**/publicclassListDemo{publicstaticvoidmain(String[]args){List<String>list=newArrayList<String>();list.add("AAA");list.add("BBB");list.add("CCC");list.add("DDD");//forearch寰鐜System.out.println("forearch閬嶅巻锛");for(Strings:list){System.out.println(s);}//杩浠e櫒寰鐜System.out.println("杩浠e櫒閬嶅巻锛");Iterator<String>it=list.iterator();while(it.hasNext()){System.out.println(it.next());}//璇诲啓鏂囦欢try{Filefile=newFile("aa.txt");FileWriterfw=newFileWriter(file);fw.write("鍛靛懙鍝掞紝AAA~~");fw.close();FileReaderfr=newFileReader(file);char[]cs=newchar[60];fr.read(cs);System.out.println("鍐呭规潵鑷鏂囦欢锛歕n"+newString(cs));}catch(Exceptione){e.printStackTrace();}}}

② php读取txt文件 然后写入数据库

<?php $file_dir="1.txt"; $fp=fopen($file_dir,"r"); $content=fread($fp,filesize($file_dir));//读文件 fclose($fp); function replaces($str)//为各字段添加'' { foreach($str as $k=>$v) { $str[$k]="'".trim($v)."'"; } return $str; } function Get_item($tmp1,$tmp2,$cont,$sq)//取得sql语句;tmp1为记录分割点,tmp2为字段分割点 { $tmp_rows=explode($tmp1,$cont); foreach($tmp_rows as $key=>$value) { $tmp_rows2[$key]=replaces(explode($tmp2,trim($value))); $sql[$key]=$sq.implode(",",$tmp_rows2[$key]).")\""; } return $sql; } $sq="\"insert into table1 (a1,a2,a3) values (";//sql的前半部分,要完善! $sql=array(); $sql=Get_item("-"," ",$content,$sq); //$db=mysql_connect("localhost","root","abc");//联接mysql,自己加 //mysql_select_db(…. foreach($sql as $v) { mysql_query($v);//执行sql; } //mysql_close($db); ?> 或者生成一个1.sql文件,再把它导入mysql;


赞 (0)