java小程序从数据库中(表)中读取数据然后创建文件夹生成txt文件

最近在写文件文件读写的功能对读写操作有了更深一层的理解。

在java中stream代表一种数据源,javaio的底层数据源。

在任何有能力产生数据源的javaio对象就可以看作是一个InputStream对象。他能产生数据源我们便能将数据取出来,java对封装的通用方法就用read()方法。

反之任何有能力接受数据源的javaio对象我们就可以看作是一个outputsteram 对象,能接受数据我们就可以调用它的write方法,

下面是一些常用的流。

基于字节流的stream:

dataOutputstream          dataInputStream

FileOutputStream           FileInputStream

基于字符流的Stream

FileWriter         FileReader

StringWriter     StringReader


输出数据:

void write(int b) 往流中写一个字节b

void write(byte b[])王字节中写一个字节数组b

void write(byte b[],int off,int len)把字节数组b中从下标off开始,长度问len的字节写入流中

最后关闭流。OutputStream是流的形式,具体可以表现为FileOutputStream的形式进行整行的写入。
可以通过“FileOutputStream”创建文件实例,之后过“OutputStreamWriter”流的形式进行存储,举例:
OutputStreamWriter pw = null;//定义一个流
pw = new OutputStreamWriter(new FileOutputStream(“D:/test.txt”),"GBK");//确认流的输出文件和编码格式,此过程创建了“test.txt”实例
pw.write("我是要写入到记事本文件的内容");//将要写入文件的内容,可以多次write
pw.close();//关闭流

outputStream

下面是我写的一个简单的小项目。



一:首先创建一个对象

package com.files.readdata;


import java.math.BigDecimal;
/**
 * 类
 * @author Frank.dai
 *
 */
public class InfoBean {

private BigDecimal seqNo;
private String billNo;
private String policyNo;
private String certiNo;
private BigDecimal amount;
private String returnCode;
private String returnDesc;

public BigDecimal getSeqNo() {
return seqNo;
}
public void setSeqNo(BigDecimal seqNo) {
this.seqNo = seqNo;
}
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public String getPolicyNo() {
return policyNo;
}
public void setPolicyNo(String policyNo) {
this.policyNo = policyNo;
}
public String getCertiNo() {
return certiNo;
}
public void setCertiNo(String certiNo) {
this.certiNo = certiNo;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getReturnCode() {
return returnCode;
}
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public String getReturnDesc() {
return returnDesc;
}
public void setReturnDesc(String returnDesc) {
this.returnDesc = returnDesc;
}



}

二:写一个来连接数据库的操作

package com.files.readdata;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DbConnection {

public static Connection getConnection(){

Connection con = null;

Properties properties = new Properties();
InputStream in = Thread.currentThread().getClass().getResourceAsStream("/database.properties");
try {
properties.load(in);
String driver = properties.getProperty("driver");
if(driver != null){
System.setProperty("jdbc.drvers", driver);
}

String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
try {
con = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, e);;
}
} catch (IOException e1) {
e1.printStackTrace();
}

return con;
}


}

三:创建对数据库操作的类

package com.files.readdata;


import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;


public class CallDatabase {

private Connection con =null;

public  void selectData(List retList) throws SQLException {

Properties properties = new Properties();
InputStream in = Thread.currentThread().getClass().getResourceAsStream("/database.properties");
String sql;
String  sqlSA;
String  sqlDW;
con = DbConnection.getConnection();
PreparedStatement pstmt;
ResultSet rs;
try {
properties.load(in);
} catch (IOException e) {

e.printStackTrace();
}
WriteFile writerFile  =  new WriteFile();
//承保对账NB
List retListNB = new ArrayList();
sql = "select seq_No,bill_No,policy_No,certi_No,amount,return_code,return_desc from t_pa_nb_list";

pstmt =  con.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
Double sumAmountNB = 0D;
while (rs.next()) {
InfoBean infoBean = new InfoBean();
BigDecimal seqNo = rs.getBigDecimal(1); // 获取的表字段换成自己需要的
String billNo = rs.getString(2);
String policyNo = rs.getString(3);
String certiNo = rs.getString(4);
BigDecimal amount = rs.getBigDecimal(5);
String returnCode = rs.getString(6);
String returnDesc = rs.getString(7);
infoBean.setSeqNo(seqNo);
infoBean.setBillNo(billNo);
infoBean.setPolicyNo(policyNo);
infoBean.setCertiNo(certiNo);
infoBean.setAmount(amount);
infoBean.setReturnCode(returnCode);
infoBean.setReturnDesc(returnDesc);
BigDecimal amountNB = infoBean.getAmount();//获取金额
   Double amNB = amountNB.doubleValue();//转换成double型
sumAmountNB = amNB+sumAmountNB;
retListNB.add(infoBean);
}

//追加对账SA
sqlSA = "select seq_No,bill_No,policy_No,certi_No,amount,return_code,return_desc from t_cs_sa_list";
pstmt = con.prepareStatement(sqlSA);
rs = pstmt.executeQuery(sqlSA);

Double sumAmountSA = 0D;
List retListSA = new ArrayList();
while (rs.next()) {
InfoBean infoBeanSA = new InfoBean();
BigDecimal seqNo = rs.getBigDecimal(1); // 获取的表字段换成自己需要的
String billNo = rs.getString(2);
String policyNo = rs.getString(3);
String certiNo = rs.getString(4);
BigDecimal amount = rs.getBigDecimal(5);
String returnCode = rs.getString(6);
String returnDesc = rs.getString(7);
infoBeanSA.setSeqNo(seqNo);
infoBeanSA.setBillNo(billNo);
infoBeanSA.setPolicyNo(policyNo);
infoBeanSA.setCertiNo(certiNo);
infoBeanSA.setAmount(amount);
infoBeanSA.setReturnCode(returnCode);
infoBeanSA.setReturnDesc(returnDesc);
BigDecimal amountSA = infoBeanSA.getAmount();//获取金额
   Double amSA = amountSA.doubleValue();//转换成double型
sumAmountSA = amSA+sumAmountSA;
retListSA.add(infoBeanSA);
}

//领取对账DW
sqlDW = "select seq_No,bill_No,policy_No,certi_No,amount,return_code,return_desc from t_cs_dw_list";
pstmt = con.prepareStatement(sqlDW);
rs = pstmt.executeQuery(sqlDW);

Double sumAmountDW = 0D;
List retListDW = new ArrayList();
while (rs.next()) {
InfoBean infoBeanDW = new InfoBean();
BigDecimal seqNo = rs.getBigDecimal(1); // 获取的表字段换成自己需要的
String billNo = rs.getString(2);
String policyNo = rs.getString(3);
String certiNo = rs.getString(4);
BigDecimal amount = rs.getBigDecimal(5);
String returnCode = rs.getString(6);
String returnDesc = rs.getString(7);
infoBeanDW.setSeqNo(seqNo);
infoBeanDW.setBillNo(billNo);
infoBeanDW.setPolicyNo(policyNo);
infoBeanDW.setCertiNo(certiNo);
infoBeanDW.setAmount(amount);
infoBeanDW.setReturnCode(returnCode);
infoBeanDW.setReturnDesc(returnDesc);
BigDecimal amount2 = infoBeanDW.getAmount();//获取金额
   Double amDW = amount2.doubleValue();//转换成double型
sumAmountDW = amDW+sumAmountDW;
retListDW.add(infoBeanDW);
}
Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
calendar.add(Calendar.DATE, Integer.valueOf(properties.getProperty("indexday"))); // 得到某一天
String yestedayDate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
String yestedayDay = new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
String path = properties.getProperty("path");
String filePath = path + yestedayDate;
String suffixs = properties.getProperty("suffixs");
String splict = properties.getProperty("splict");
String prefixion = properties.getProperty("prefixion");//NB
String prefix = properties.getProperty("prefix");//SA
String pref = properties.getProperty("pref");//DW
if(prefixion.equals("NB")){
String filePathName = filePath+splict+prefixion+yestedayDay+ "."+suffixs;
writerFile.writeFile(filePath,filePathName,retListNB,yestedayDate,sumAmountNB); 
}
if(prefix.equals("SA")){

String filePathName = filePath+splict+prefix+yestedayDay+ "."+suffixs;
writerFile.writeFileSA(filePath,filePathName,retListSA,yestedayDate,sumAmountSA);
}
if(pref.equals("DW")){
String filePathName = filePath+splict+pref+yestedayDay+ "."+suffixs;
writerFile.writeFileDW(filePath,filePathName,retListDW,yestedayDate,sumAmountDW);
}
}

/**
* 结息文件
* @param settlementBeanList
* @throws SQLException
*/
public void selectSettlementBean(List settlementBeanList) throws SQLException{

Properties properties = new Properties();

InputStream in = Thread.currentThread().getClass().getResourceAsStream("/database.properties");

con = DbConnection.getConnection();
PreparedStatement ptmt;
String sqlSM;
ResultSet rs;
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
WriteFile writeFileSM = new WriteFile();
List settlementBeanlist = new ArrayList(); 
sqlSM = "select seq_no,policy_no,account_type,interest_rate,settle_int_sum,start_capital,end_capital,start_balance,end_balance,settle_date from t_settlement_list";
   ptmt = con.prepareStatement(sqlSM);
   rs = ptmt.executeQuery(sqlSM);
   while(rs.next()){
    SettlementBean  settlement = new SettlementBean();
    BigDecimal seqNo = rs.getBigDecimal(1); // 获取的表字段换成自己需要的
String policyNo = rs.getString(2);
String accountType = rs.getString(3);
BigDecimal  interestRate = rs.getBigDecimal(4);
BigDecimal settleIntSum  = rs.getBigDecimal(5);
BigDecimal startCapital  = rs.getBigDecimal(6);
BigDecimal endCapital    = rs.getBigDecimal(7);
BigDecimal startBalance  = rs.getBigDecimal(8);
BigDecimal endBalance    = rs.getBigDecimal(9);
Date settleDate        = rs.getDate(10);
settlement.setSeqNo(seqNo);
settlement.setPolicyNo(policyNo);
settlement.setAccountType(accountType);
settlement.setInterestRate(interestRate);
settlement.setSettleIntSum(settleIntSum);
settlement.setStartCapital(startCapital);
settlement.setEndCapital(endCapital);
settlement.setStartBalance(startBalance);
settlement.setEndBalance(endBalance);
settlement.setSettleDate(settleDate);
settlementBeanlist.add(settlement);



   }
   Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
calendar.add(Calendar.DATE, Integer.valueOf(properties.getProperty("indexday"))); // 得到某一天
String yestedayDate = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
String yestedayDay = new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
String path = properties.getProperty("path");
String filePath = path + yestedayDate;
String suffixs = properties.getProperty("suffixs");
String splict = properties.getProperty("splict");
String pre = properties.getProperty("pre");//INV
String suff = properties.getProperty("suff");//bat
String filePathName = filePath+splict+pre+yestedayDay+"001"+ "."+suffixs;
String emptyFile = filePathName +"."+suff;
writeFileSM.writeFileINV(filePath,filePathName,settlementBeanlist,yestedayDate,emptyFile); 
}



}

四:创建一个写文件的操作

package com.files.readdata;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;


public class WriteFile {
 
/**将数据内容写到txt文件中
 * NB领取对账
 * @param filePath
 * @param filePathName
 * @param retList1
 */


 public  void writeFile(String filePath,String filePathName,List retListNB,String yestedayDate,Double sumAmountNB){



 File file = new File(filePath); // 自定义文件路径
 File file1 = new File(filePathName); // 自定义文件路径
 
 if(!file.exists() && !file.isDirectory()){
 
 file.mkdir();
 if (!file1.exists()) {
 try {
 file1.createNewFile();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }else{
 System.out.println("文件已替换");
 }
 }else{
 System.out.println("文件夹已存在");
 }
   String  encoding = "UTF-8";
OutputStreamWriter write;
try {
write = new OutputStreamWriter(new FileOutputStream(file1),encoding);
BufferedWriter writer = new BufferedWriter(write);
System.out.println("汇总金额:"+sumAmountNB);
String returnCode = "0";
String returnDesc = "成功";
System.out.println("交易日期:"+yestedayDate);
int account = retListNB.size();
System.out.println("总笔数:"+account);
String strr = yestedayDate+"|"+sumAmountNB+"|"+ account+"|"+returnCode+"|"+returnDesc;
writer.write(strr+"\r\n");
System.out.println(strr);
for (InfoBean ib : retListNB) {
String str = ib.getSeqNo()+"|"+ib.getBillNo()+"|"+ib.getPolicyNo()+"|"+ib.getCertiNo()+"|"+ib.getAmount()+"|"+ib.getReturnCode()+"|"+ib.getReturnDesc();
System.out.println(str);
// writer.write(ib.toString()); // 输出流写入到文件中
writer.write(str+"\r\n");

}
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
 }
 /**
  * 追加对账
  * @param filePath
  * @param filePathName
  * @param retListSA
  * @param yestedayDate
  * @param sumAmountSA
  */
 public  void writeFileSA(String filePath,String filePathName,List retListSA,String yestedayDate,Double sumAmountSA){



 File file = new File(filePath); // 自定义文件路径
 File file1 = new File(filePathName); // 自定义文件路径
 
 if(!file.exists() && !file.isDirectory()){
 
 file.mkdir();
 if (!file1.exists()) {
 try {
 file1.createNewFile();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }else{
 System.out.println("文件已替换");
 }
 }else{
 System.out.println("文件夹已存在");
 }
   String  encoding = "UTF-8";
OutputStreamWriter write;
try {
write = new OutputStreamWriter(new FileOutputStream(file1),encoding);
BufferedWriter writer = new BufferedWriter(write);
System.out.println("SA汇总金额:"+sumAmountSA);
String returnCode = "0";
String returnDesc = "成功";
System.out.println("SA交易日期:"+yestedayDate);
int accountSA = retListSA.size();
System.out.println("SA总笔数:"+accountSA);
String strr = yestedayDate+"|"+sumAmountSA+"|"+ accountSA+"|"+returnCode+"|"+returnDesc;
writer.write(strr+"\r\n");
System.out.println(strr);
for (InfoBean ib : retListSA) {
String str = ib.getSeqNo()+"|"+ib.getBillNo()+"|"+ib.getPolicyNo()+"|"+ib.getCertiNo()+"|"+ib.getAmount()+"|"+ib.getReturnCode()+"|"+ib.getReturnDesc();
System.out.println(str);
// writer.write(ib.toString()); // 输出流写入到文件中
writer.write(str+"\r\n");

}
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
 
 /**
  * 承保对账
  * @param filePath
  * @param filePathName
  * @param retListDW
  * @param yestedayDate
  * @param sumAmountDW
  */
 public  void writeFileDW(String filePath,String filePathName,List retListDW,String yestedayDate,Double sumAmountDW){



 File file = new File(filePath); // 自定义文件路径
 File file1 = new File(filePathName); // 自定义文件路径
 if(!file.exists() && !file.isDirectory()){
 
 file.mkdir();
 if (!file1.exists()) {
 try {
 file1.createNewFile();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }else{
 System.out.println("文件已替换");
 }
 }else{
 System.out.println("文件夹已存在");
 }
   String  encoding = "UTF-8";
OutputStreamWriter write;
try {
write = new OutputStreamWriter(new FileOutputStream(file1),encoding);
BufferedWriter writer = new BufferedWriter(write);
System.out.println("SA汇总金额:"+sumAmountDW);
String returnCode = "0";
String returnDesc = "成功";
System.out.println("SA交易日期:"+yestedayDate);
int accountDW = retListDW.size();
System.out.println("SA总笔数:"+accountDW);
String strr = yestedayDate+"|"+sumAmountDW+"|"+ accountDW+"|"+returnCode+"|"+returnDesc;
writer.write(strr+"\r\n");
System.out.println(strr);
for (InfoBean ib : retListDW) {
String str = ib.getSeqNo()+"|"+ib.getBillNo()+"|"+ib.getPolicyNo()+"|"+ib.getCertiNo()+"|"+ib.getAmount()+"|"+ib.getReturnCode()+"|"+ib.getReturnDesc();
System.out.println(str);
// writer.write(ib.toString()); // 输出流写入到文件中
writer.write(str+"\r\n");

}
writer.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
 * 结息操作
 * @param filePath
 * @param filePathName
 * @param settlementBeanlist
 * @param yestedayDate
 * @param emptyFile
 */
 public void writeFileINV(String filePath,String filePathName,List settlementBeanlist,String yestedayDate,String emptyFile){

File file = new File(filePath);
File file1 = new File(filePathName);
File file2 = new File(emptyFile);
if(!file.exists() && !file.isDirectory()){
file.mkdir();
if(file1.exists() && file1.isDirectory()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("文件已替换");
}
if(file2.exists() && file2.isDirectory()){
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("文件已替换");
}
 
}else{
System.out.println("文件夹已存在");
}
String encoding = "UTF-8";
OutputStreamWriter outWrite ;
try {
outWrite = new  OutputStreamWriter(new FileOutputStream(file1),encoding);

for(SettlementBean stb: settlementBeanlist){

String sett = stb.getSeqNo()+"|"+stb.getPolicyNo()+"|"+stb.getAccountType()+"|"+stb.getInterestRate()+"|"+stb.getSettleIntSum()+"|"+stb.getStartCapital()+"|"+stb.getEndCapital()+"|"+stb.getStartBalance()+"|"+stb.getEndBalance()+"|"+stb.getSettleDate();
outWrite.write(sett+"\r\n");
}
outWrite.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
//在生成txt文件之后生成bat文件
OutputStreamWriter outWritebat ;
try {
 
//生成空的.bak文件
outWritebat = new  OutputStreamWriter(new FileOutputStream(file2),encoding);
outWritebat.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
 }
 
}

五:主函数:

package com.files.readdata;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 主函数运行
 * 
 * @author Frank.dai
 *
 */
public class Execution {


public static void main(String[] args) {

CallDatabase callDatabase = new CallDatabase();
List retList = new ArrayList();
List settlementBeanList = new ArrayList();
try {
callDatabase.selectData(retList);
callDatabase.selectSettlementBean(settlementBeanList);
} catch (SQLException e) {
e.printStackTrace();
}


}
}


你可能感兴趣的:(java开发)