當前位置:編程學習大全網 - 編程語言 - java程序中怎樣用文件存儲數據

java程序中怎樣用文件存儲數據

對於壹些小文件,我們可以壹次性讀取它的所有字節,然後壹次提交到數據庫

///

/// 這個方法演示了如何壹次提交所有的字節。這樣導致的結果是:應用程序立即需要申請等同於文件大小的內存

static void SubmitFileByOnce() {

string file = @"F:\功夫熊貓.rmvb";//文件大小為519MB

byte[] buffer = File.ReadAllBytes(file);

using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true")) {

using (SqlCommand cmd = conn.CreateCommand())

{

cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";

cmd.Parameters.AddRange(

new[]

{

new SqlParameter("@fileName",file),

new SqlParameter("@fileContents",buffer)

});

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

}

}

}

但是,上面的方法有幾個問題,主要體現在如果文件比較大的話

它需要壹次性很大的內存,具體數據等同於文件大小。因為File.ReadAllBytes方法是將所有字節全部讀入到內存。

它會導致提交失敗,就是因為數據太大了。數據庫也會拒絕。

那麽,我就對這個方法做了壹下改進,將文件拆分為5MB壹段,也就是說,此時每次申請的內存只有5MB。這就大大地提高了可用性。

/// 這個方法是將文件切分為5MB的塊,每次只是提交5MB,所以可能多次提交,但內存占用就比較小

static void SubmitFileStepByStep() {

string file = @"F:\功夫熊貓.rmvb";//以這個文件為例,大小為519MB,壹***需要的時間大約94秒。還是有點慢的,所以還可能需要進行壓縮

FileStream fs = new FileStream(file, FileMode.Open);

byte[] buffer = new byte[5 * 1024 * 1024];

int readCount;

using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))

{

conn.Open();

while ((readCount = fs.Read(buffer, 0, buffer.Length)) > 0)

{

using (SqlCommand cmd = conn.CreateCommand())

{

cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";

cmd.Parameters.AddRange(

new[]

{

new SqlParameter("@fileName",file),

new SqlParameter("@fileContents",buffer)

});

cmd.ExecuteNonQuery();

}

}

conn.Close();

}

}

這樣的話,有壹個後果就是壹個文件,可能在數據庫中會有多條記錄。所以在讀取的時候,我們需要對其進行合並

static void DownloadFile() {

string file = @"F:\功夫熊貓.rmvb";

string destfile = @"E:\Temp\Temp.wmv";

using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))

{

using (SqlCommand cmd = conn.CreateCommand())

{

cmd.CommandText = "SELECT FileContents FROM Files WHERE FileName=@fileName";

cmd.Parameters.AddRange(

new[]

{

new SqlParameter("@fileName",file),

});

conn.Open();

SqlDataReader reader = cmd.ExecuteReader();

FileStream fs = new FileStream(destfile, FileMode.Append, FileAccess.Write);

while (reader.Read())

{

byte[] buffer = (byte[])reader[0];

fs.Write(buffer, 0, buffer.Length);

}

fs.Close();

reader.Close();

conn.Close();

}

}

}

  • 上一篇:哈佛大學的王牌專業
  • 下一篇:手機中有哪些電子物料
  • copyright 2024編程學習大全網