java如何从数据库读取数据并写入txt文件?

java如何从数据库读取数据并写入txt文件?,第1张

写Java程序时经常碰到要读如txt或写入txt文件的情况,但是由于要定义好多变量,经常记不住,每次都要查,特此整理一下,简单易用,方便好懂!

[java] view plain copy

package edu.thu.keyword.test  

  

import java.io.File  

import java.io.InputStreamReader  

import java.io.BufferedReader  

import java.io.BufferedWriter  

import java.io.FileInputStream  

import java.io.FileWriter  

  

public class cin_txt {  

    static void main(String args[]) {  

        try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw  

  

            /* 读入TXT文件 */  

            String pathname = "D:\\twitter\\13_9_6\\dataset\\en\\input.txt" // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径  

            File filename = new File(pathname) // 要读取以上路径的input。txt文件  

            InputStreamReader reader = new InputStreamReader(  

                    new FileInputStream(filename)) // 建立一个输入流对象reader  

            BufferedReader br = new BufferedReader(reader) // 建立一个对象,它把文件内容转成计算机能读懂的语言  

            String line = ""  

            line = br.readLine()  

            while (line != null) {  

                line = br.readLine() // 一次读入一行数据  

            }  

  

            /* 写入Txt文件 */  

            File writename = new File(".\\result\\en\\output.txt") // 相对路径,如果没有则要建立一个新的output。txt文件  

            writename.createNewFile() // 创建新文件  

            BufferedWriter out = new BufferedWriter(new FileWriter(writename))  

            out.write("我会写入文件啦\r\n") // \r\n即为换行  

            out.flush() // 把缓存区内容压入文件  

            out.close() // 最后记得关闭文件  

  

        } catch (Exception e) {  

            e.printStackTrace()  

        }  

    }  

}

不管你用什么东东,你下文件总得给出文件地址或者文件参数再下载,所以本质上没太多区别。

你的逻辑是从数据库拿数据然后生成文件,然后再下载;

首先你得把数据拿出来,然后用io类生成临时文件,如果为了偷懒,想直接给个url就完了,那就把文件生在工程根目录下比如:proname/downtemp/1234.doc

然后把绝对路径给出,就可以下载了 ,这中间可能要跳转一下,因为你是临时产生,不是直接下载。

第一个类:

package totabel.action

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import javax.swing.JOptionPane

import topdf.TableToPdf

import totabel.view.TabelData

import totabel.xls.ExcelDemo

public class TableAction implements ActionListener {

TabelData data

public TableAction(TabelData data) {

this.data = data

}

public void actionPerformed(ActionEvent e) {

String str = e.getActionCommand()

if ("添加".equals(str)) {

data.addData()

} else if ("导出到Excel".equals(str)) {

ExcelDemo demo = new ExcelDemo()

demo.method(data)

} else if ("删除".equals(str)) {

if (data.getRow() != -1) {

data.delRow()

} else {

JOptionPane.showMessageDialog(null, "请选择要删除的行!")

}

}else if("从Excel导入".equals(str)){

data.getXlsInfo()

}else if("从Excel导入到数据库".equals(str)){

data.toDb()

}else if("从table导出到pdf".equals(str)){

TableToPdf pdf=new TableToPdf()

pdf.newPage(data)

}else if("计算学分".equals(str)){

data.getXlsInfoToCredit()

}

}

}

第二个类:数据库连接

package totabel.db

import java.sql.Connection

import java.sql.DriverManager

import java.sql.ResultSet

import java.sql.SQLException

import java.sql.Statement

public class JdbcConnection {

private static JdbcConnection con

public static JdbcConnection getCon() {

if (con == null) {

con = new JdbcConnection()

}

return con

}

public Connection getConnection() {

Connection connection=null

try {

Class.forName("oracle.jdbc.OracleDriver")

String url = "jdbc:oracle:thin:@127.0.0.1:1521:oracle"

String user = "scott"

String password = "tiger"

connection = DriverManager.getConnection(url, user,

password)

} catch (ClassNotFoundException e) {

e.printStackTrace()

} catch (SQLException e) {

e.printStackTrace()

}

return connection

}

// public static void main(String[] args) {

// JdbcConnection connection=new JdbcConnection()

// connection.getConnection("asd", "99")

// }

}

第三个类:主类(入口)

package totabel.db

import java.sql.Connection

import java.sql.DriverManager

import java.sql.ResultSet

import java.sql.SQLException

import java.sql.Statement

public class JdbcConnection {

private static JdbcConnection con

public static JdbcConnection getCon() {

if (con == null) {

con = new JdbcConnection()

}

return con

}

public Connection getConnection() {

Connection connection=null

try {

Class.forName("oracle.jdbc.OracleDriver")

String url = "jdbc:oracle:thin:@127.0.0.1:1521:oracle"

String user = "scott"

String password = "tiger"

connection = DriverManager.getConnection(url, user,

password)

} catch (ClassNotFoundException e) {

e.printStackTrace()

} catch (SQLException e) {

e.printStackTrace()

}

return connection

}

// public static void main(String[] args) {

// JdbcConnection connection=new JdbcConnection()

// connection.getConnection("asd", "99")

// }

}

第四个类:

package totabel.xls

import java.io.File

import java.io.IOException

import java.util.Vector

import java.util.regex.Matcher

import java.util.regex.Pattern

import javax.swing.JOptionPane

import totabel.view.TabelData

import jxl.Cell

import jxl.Sheet

import jxl.Workbook

import jxl.read.biff.BiffException

import jxl.write.Label

import jxl.write.WritableSheet

import jxl.write.WritableWorkbook

import jxl.write.WriteException

import jxl.write.biff.RowsExceededException

public class ExcelDemo {

/**

*

* @param args

*/

private Vector title = new Vector()

private Vector[] array

// public static void main(String[] args) {

// ExcelDemo demo = new ExcelDemo()

// demo.getXlsInfo()

//

// }

public void method(TabelData table) {

int row = table.getRowSize()

int column = table.getColumnSize()

WritableWorkbook book = null

Vector title = table.setTitle()

Object[] str = title.toArray()

try {

book = Workbook.createWorkbook(new File("test.xls"))

WritableSheet sheet = book.createSheet("成绩表", 0)

for (int i = 0i <str.lengthi++) {

sheet.addCell(new Label(i, 0, (String) str[i]))

}

for (int i = 1i <row + 1i++) {

for (int j = 1j <column + 1j++) {

sheet.addCell(new Label(j - 1, i, table.getTableInfo(i - 1,

j - 1)))

}

}

book.write()

JOptionPane.showMessageDialog(null, "导出完成!")

} catch (IOException e) {

e.printStackTrace()

} catch (RowsExceededException e) {

e.printStackTrace()

} catch (WriteException e) {

e.printStackTrace()

} finally {

try {

book.close()

} catch (WriteException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

}

/**

* 输出Excel的数据到表单

*

* @return

*/

public Vector getXlsInfo() {

Vector v = new Vector()

jxl.Workbook rwb = null

int index = 0

try {

rwb = jxl.Workbook.getWorkbook(new File("test.xls"))

Sheet[] sheet = rwb.getSheets()

for (int i = 0i <sheet.lengthi++) {

int rs = sheet[i].getRows()

array = new Vector[rs - 1]

for (int j = 1j <rsj++) {

Cell[] cell = sheet[i].getRow(j)

Vector info = new Vector()

for (int k = 0k <cell.lengthk++) {

info.add(cell[k].getContents())

}

array[index] = info

index++

v.add(info)

}

Cell[] titleCell = sheet[i].getRow(0)

for (int j = 0j <titleCell.lengthj++) {

title.add(titleCell[j].getContents())

}

}

} catch (BiffException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

rwb.close()

}

return v

}

public Vector getXlsInfoToCredit() {

Vector v = new Vector()

jxl.Workbook rwb = null

try {

rwb = jxl.Workbook.getWorkbook(new File("d:/test/信科0821(南迁).xls"))

Sheet[] sheet = rwb.getSheets()

for (int i = 0i <sheet.lengthi++) {

int rs = sheet[i].getRows()

array = new Vector[rs - 1]

for (int j = 1j <rsj++) {

Cell[] cell = sheet[i].getRow(j)

Vector info = new Vector()

for (int k = 0k <cell.lengthk++) {

// if(){

Pattern p = Pattern.compile("[0-9]{1,}")

Matcher m = p.matcher(cell[k].getContents())

if (m.matches()) {

int score = Integer.valueOf(cell[k].getContents())

float result = getScore(score)

info.add(result)

} else {

info.add(cell[k].getContents())

}

}

v.add(info)

}

Cell[] titleCell = sheet[i].getRow(0)

for (int j = 0j <titleCell.lengthj++) {

title.add(titleCell[j].getContents())

}

}

} catch (BiffException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

rwb.close()

}

return v

}

public float getScore(int n) {

float score = n

if (n <60) {

score = 0

return score

} else {

if (n >= 60 &&n <= 63) {

score = (float) 1.0

} else if (n >= 64 &&n <= 67) {

score = (float) 1.3

} else if (n >= 68 &&n <= 71) {

score = (float) 1.7

} else if (n >= 72 &&n <= 75) {

score = (float) 2.0

} else if (n >= 76 &&n <= 79) {

score = (float) 2.3

} else if (n >= 80 &&n <= 83) {

score = (float) 2.7

} else if (n >= 84 &&n <= 87) {

score = (float) 3.0

} else if (n >= 88 &&n <= 91) {

score = (float) 3.3

} else if (n >= 92 &&n <= 95) {

score = (float) 3.7

} else if (n >= 96 &&n <= 100) {

score = (float) 4.0

}

return score

}

}

public Vector getTitle() {

// getXlsInfo()

return title

}

public Vector[] getArray() {

getXlsInfo()

return array

}

}

因为时间问题就没有再写了,上面是我以前做的,不懂就q我


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6705891.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-27
下一篇 2023-03-27

发表评论

登录后才能评论

评论列表(0条)

保存