使用Java的IO流拼接SQL语句

使用IO流拼接SQL语句
读取txt文件的内容;然后拼接成SQL语句后输出到txt文件。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class IOStreams {

	public static void main(String[] args) {
		// 读数据(相对路径)
		String readFileName = ".\\source\\test_1029.txt"; 
		Collection coll = readFiles(readFileName);
		System.out.println("上传的数据总条数:"+ coll.size());
		
		// 写数据(相对路径)
		String writeFileName = ".\\source\\test_point_1029.txt";
		int num = writeFiles(writeFileName, coll);
		System.out.println("写入的数据总条数:" + num);
	}
	
	/**
	 * 读取txt文件入集合
	 * @param pathName
	 * @return
	 * @throws IOException 
	 */
	public static Collection readFiles(String pathName) {
		Collection coll = new ArrayList<>();
		File file = null;
		InputStreamReader reader = null;
		String line = null;
		try {
			file = new File(pathName);
			// 建立一个输入流对象reader
			reader = new InputStreamReader(new FileInputStream(file));
			// 建立一个对象,它把文件内容转成计算机能读懂的语言
            BufferedReader br = new BufferedReader(reader);
            while (br.ready()) { 
            	// (line = br.readLine())!=null,会出现漏读首行,文末行为null
            	// 可以用br.ready()解决
            	// 一次读入一行数据  
                line = br.readLine();
                //System.out.println(line);
                // 添加
                coll.add(line);
            } 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null != reader)
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return coll;
	}
	
	/**
	 * 把拼接后的sql语句写回txt文件
	 * @param pathName   文件的路径
	 * @param line	数据
	 */
	public static int writeFiles(String pathName,Collection coll){
		File writename = new File(pathName);
		BufferedWriter out = null;
		// 计数,统计写入的条数
		int count = 0;
		try {
			// 每次都创建新文件 
			writename.createNewFile(); 
			out = new BufferedWriter(new FileWriter(writename));  
			for(Iterator iter = coll.iterator(); iter.hasNext();){
				// \r\n即为换行
				out.write("INSERT INTO test (phone,souce) VALUES ('"+iter.next()+"','test');\r\n");   
		        out.flush(); // 把缓存区内容压入文件  
		        count ++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null != out)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		}
		return count;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章