JAVA中如何将生成的数据写入到文件中?

JAVA中如何将生成的数据写入到文件中?,第1张

packagecom.pig.database.file.txt

importjava.io.File

importjava.io.FileOutputStream

importjava.io.IOException

importjava.io.PrintStream

/**

*@authorzhuruhong

*

*若要变更这个产生的类别注解的范本,请移至

*视窗>喜好设定>Java>程式码产生>程式码和注解

*/

publicclassWriteTxtFileByName{

privateStringfilename=null

publicWriteTxtFileByName(Stringfilename){

this.filename=filename

}

publicvoidwriteFileByName(Stringcontent){

FiledocFile=newFile(filename)

try{

docFile.createNewFile()

FileOutputStreamtxtfile=newFileOutputStream(docFile)

PrintStreamp=newPrintStream(txtfile)

p.println(content)

txtfile.close()

p.close()

}catch(IOExceptione){

e.printStackTrace()

}

}

publicstaticvoidmain(String[]args){

WriteTxtFileByNamewfbn=newWriteTxtFileByName("title")

wfbn.writeFileByName("content")

}

}

给你一个实例。

帮你临时写了一个大概的.只能说保证简单运行,既然是你自己的毕业设计,缓存,文件名获取这些方面就你自己去完善了.下面是实现代码.注释没时间就没写了.都是很简单的代码,应该能看得明白.

注意点1:数据库中关于文件内容的数据类型最好是我写的那样.以前有什么blob或者image类型的,其实就算用varchar(max)也一样可以实现.但是微软SQL Server的手册上已经明确推荐varbinary](max)类型.具体看你自己选择.

注意点2:因为在从数据库读取的实现上,只是将文件保存至磁盘,所以只return null,如果有需要,可以自己返回file

--------------------------------数据库----------------------------

CREATE TABLE [dbo].[savedFile](

[fileID] [int] IDENTITY(1,1) NOT NULL,

[fileName] [nvarchar](200) NOT NULL,

[fileContent] [varbinary](max) NOT NULL,

[fileLength] [bigint] NOT NULL,

CONSTRAINT [PK_savedFile] PRIMARY KEY CLUSTERED

(

[fileID] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

) ON [PRIMARY]

GO

SET ANSI_PADDING OFF

GO

-----------------------------------简单实现的java类------------------------------------------

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.FileOutputStream

import java.io.IOException

import java.io.OutputStream

import java.sql.Connection

import java.sql.DriverManager

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.sql.SQLException

public class Test {

/**

* @param args

*/

public static void main(String[] args) {

//int saveResult = saveFileToDB()

//System.out.println("成功保存" + saveResult + "个文件至数据库中")

openFileFromDB()

}

public static File openFileFromDB() {

String path = "E:\\1.JPG"

File file = new File(path)

String sqlString = "select * from savedfile"

ResultSet rSet = null

PreparedStatement pstmt = null

Connection connection = null

try {

if (connection == null || connection.isClosed()) {

connection = createConnection()

connection.setAutoCommit(false)

}

pstmt = connection.prepareStatement(sqlString)

rSet = pstmt.executeQuery()

connection.commit()

while (rSet.next()) {

OutputStream os = new FileOutputStream(file)

int length = rSet.getInt("fileLength")

byte[] content = rSet.getBytes("fileContent")

os.write(content, 0, length)

}

} catch (SQLException e) {

try {

connection.rollback()

} catch (SQLException e1) {

e1.printStackTrace()

}

e.printStackTrace()

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

closeAll(connection, pstmt, rSet)

}

return null

}

public static int saveFileToDB() {

String sqlString = "INSERT INTO savedFile VALUES(?,?,?)"

PreparedStatement pstmt = null

Connection connection = null

int noOfRows = 0

String path = "D:\\DSC00727.JPG"

File file = new File(path)

FileInputStream fis = null

try {

fis = new FileInputStream(file)

} catch (FileNotFoundException e) {

System.err.println("文件 " + file.getPath() + " 不存在。")

return -1

}

try {

if (connection == null || connection.isClosed()) {

connection = createConnection()

}

connection.setAutoCommit(false)

pstmt = connection.prepareStatement(sqlString)

pstmt.setString(1, file.getName())

pstmt.setBinaryStream(2, fis)

pstmt.setLong(3, file.length())

noOfRows = pstmt.executeUpdate()

connection.commit()

} catch (SQLException e) {

try {

connection.rollback()

} catch (SQLException e1) {

e1.printStackTrace()

}

e.printStackTrace()

} finally {

closeAll(connection, pstmt, null)

}

return noOfRows

}

private static Connection createConnection() {

Connection connection = null

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")

} catch (ClassNotFoundException e) {

e.printStackTrace()

}

try {

connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433DataBaseName=EcrParts", "sa", "ok")

} catch (SQLException e) {

e.printStackTrace()

}

return connection

}

public static void closeAll(Connection connection, PreparedStatement pstmt,

ResultSet rSet) {

if (rSet != null) {

try {

rSet.close()

} catch (SQLException e) {

e.printStackTrace()

}

}

if (pstmt != null) {

try {

pstmt.close()

} catch (SQLException e) {

e.printStackTrace()

}

}

try {

if (connection != null) {

connection.close()

}

} catch (SQLException e) {

e.printStackTrace()

}

}

}


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

原文地址:https://54852.com/tougao/8102680.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存