Reading to text file from MySQL - java

I'm trying to store a text file in a MySQL database, and when needed, save it to a file.
To save the file, I do:
public void saveFile_InDB(File file)
{
try {
String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, new Date().toString());
statement.setString(2, new Date().toString());
InputStream inputStream = new FileInputStream(file);
statement.setBinaryStream(3, inputStream);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("File saved sucessfully.");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
And to retreive and save the file:
public void retrieveFile_fromDB()
{
try {
Statement stmt = (Statement) conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
FileOutputStream fos = new FileOutputStream("file.txt");
if (res.next()) {
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
}
} catch (IOException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
} catch (SQLException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
}
Storing the file works, but when I try to retrieve and save it, nothing is stored in the output file?

if you want read file from db Mysql
change this part in your code
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
use this code read array of bytes
byte [] bs=res.getBytes("fileName");
fos.write(bs);
it will work
if you return multiple files from db you must declare
FileOutputStream fos = new FileOutputStream("file.txt");
inside while loop and change name of file to avoid overriding

You do not seem to put into the database the things that the column names describe?
fileName and time are for example both set to a timestamp, and clientName is set to the contents of the file. When you later try to select based on clientName, you are actually selecting based on the contents of the file.
Furthermore, when reading the data, you are reading the blob data from the column fileName, but this is wrong because:
fileName contains new Date().toString(), not the contents of the file
fileName should surely contain the file's name, not its contents?

Related

file got corrupted during blob to file conversion (java)

why my download file always got corrupted.
I have a code that will upload file using blob.
the code is
InputStream inputStream = new FileInputStream(new File(filePath)); //the file to upload
pst.setBinaryStream(15, inputStream); //to upload the selected file
it's successfully upload to my sql data base but when I try to download it, it always got corrupted.
below is my code to download the file from sql.
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url1 = "jdbc:sqlserver://ets88-spare:1433;databaseName=users;user=sa;password=test";
Connection conn1 = DriverManager.getConnection(url1);
String query1 = "SELECT * FROM ets_verification";
Statement state = conn1.createStatement();
ResultSet rs = state.executeQuery(query1);
while (rs.next())
{
String boardname = jboardName.getSelectedItem().toString();
String sn = jserialNumber.getText();
String status = jverificationStatus.getSelectedItem().toString();
String filename = boardname + "_" + "_" + sn + "_"+ status;
byte[] array = rs.getBytes(16);
FileOutputStream fos = new FileOutputStream("c:\\" + filename + ".rar");
fos.write(array);
fos.close();
System.out.println("array:" + array);
}
}
catch (ClassNotFoundException | SQLException e)
{
jnote.setText(e.toString());
System.out.println("error" + e.toString());
} catch (IOException ex) {
Logger.getLogger(ets_verification.class.getName()).log(Level.SEVERE, null, ex);
}
You could try.
Tested in a ORACLE DB.
(...)
Blob blob = rs.getBlob(16);
if (blob != null) {
byte[] b = blob.getBytes(1, (int) blob.length());
try (FileOutputStream fos = new FileOutputStream("PATH/TO/FILE/FILENAME.rar")){
fos.write(file);
}catch (IOException ex) {
//Do something
}
}
(...)

using java jdbc downloading blob(audio) from mysql.Things goes well, but I cant play the audio

As the title described, when I download the blob(audio) file from MySQL, things goes well and I get the file, but I can't play the audio immediately, unless I terminate the progress.
I guess the audio file is being occupated by the program, if so how can I solve this problem without terminate the program. thx!
Here the code:
public void downloadAudio(int documentid,String pathname) {
String sql = "SELECT storage FROM chatroom_tool WHERE documentid=?";
ResultSet rSet = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, documentid);
rSet = pstmt.executeQuery();
File file = new File(pathname);
FileOutputStream output = new FileOutputStream(file);
System.out.println("writing to file: " + file.getAbsolutePath());
while (rSet.next()) {
InputStream inputStream = rSet.getBinaryStream("storage");
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
output.write(buffer);
}
}
System.out.println("downLoad success +++++");
} catch (SQLException | IOException e) {
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is the picture when I open the audio without terminating the program.
image
inputStream.read does not have to fill the array with data completely, it returns the number of bytes it read. You must use the return value when you write the data to the output stream.
while ((bytes =inputStream.read(buffer)) >0)
output.write(buffer, bytes);
Also you have to close the output stream - Windows does not let other apps open the file as long as your program has it open

Values not being set properly in excel when trying to insert records from Selenium

I'm trying to store UserID, Password & EmailID which are being passed to the website that I'm trying to automate using selenium into an excel file.
The problem is that the excel file that is being generated is storing UserID twice , the other two values are not being written to the excel.
What I want is to write userID, EmailID & Password next to each other.
My code is as follows:
MfpCreateAccountPage createAccount =PageFactory.initElements(driver, MfpCreateAccountPage.class);
createAccount.userDetails(randomAlphaNumericvalue, randomAlphaNumericvalue.toLowerCase()+ "#gmail.com" , randomAlphaNumericvalue);
ExcelDriven.setCelldata(randomAlphaNumericvalue, 0, 0);
ExcelDriven.setCelldata(randomAlphaNumericvalue.toLowerCase()+ "#gmail.com", 0, 1);
ExcelDriven.setCelldata(randomAlphaNumericvalue, 0, 2);
Below is my code to write data into excel
public static String setCelldata(String text,int rownum,int col) throws IOException
{
wb= new HSSFWorkbook();
//sheet=wb.getSheet("script");
sheet = wb.createSheet("Script");
row=sheet.createRow(rownum);
cell=row.createCell(rownum);
cell.setCellValue(text);
cell = row.createCell(col);
cell.setCellValue(text);
cell = row.createCell(col);
cell.setCellValue(text);
String celldata1= cell.getStringCellValue();
FileOutputStream fos = null;
try{
fos = new FileOutputStream(new File("D:\\Data.xls"));
wb.write(fos);
}
catch (IOException e){
e.printStackTrace();
}
finally{
if(fos!= null){
try{
fos.flush();
fos.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
return celldata1;
}
Could someone tell me where I'm going wrong? Thanks!!!

Reading zip archive from database

I have a zip file which I store in the database as a blob field. When I want to download it from it the zip file is corrupted. I can open it only from 7zip. The file is ok when I try to open it before upload it in the DB and when is in the DB. When I retrieve the file from the database as a blob I get this error when try to unzip it on unix
Archive: test.zip
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of test.zip or
test.zip.zip, and cannot find test.zip.ZIP, period.
Here is the code when I retrieve the zip from the database :
public oracle.sql.BLOB GetBlob(Connection myConn,
CallableStatement cstmt) throws Exception {
String strSql = null;
BLOB tempBlob = null;
try {
strSql = .... // Here is the sql procedure which I called to retrieve the blobl field.
cstmt = myConn.prepareCall(strSql);
cstmt.registerOutParameter(1, OracleTypes.BLOB);
cstmt.setLong(2, request_id);
cstmt.execute();
tempBlob = (oracle.sql.BLOB)cstmt.getObject(1);
int bufsize = tempBlob.getBufferSize();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return tempBlob;
Here is the reading :
oracle.sql.BLOB tempBlob = null;
Connection myConn = null;
CallableStatement cstmt = null;
try {
myConn = DBHelper.getConnection();
if (null == myConn)
throw new SQLException();
tempBlob = GetBlob(myConn, cstmt);
int bufsize = tempBlob.getBufferSize();
InputStream in = tempBlob.getBinaryStream();
int length = 0;
byte buf[] = new byte[bufsize];
while ((in != null) && ((length = in.read(buf)) != -1)) {
out.write(buf, 0, length);
}
in.close();
// out.flush();
// out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != myConn) {
try {
myConn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (cstmt != null) {
try {
cstmt.close();
} catch (SQLException e) {
}
}
}
Could somebody help me.
Thanks in advance.
Compare the files before and after. The difference should give you some hint what is going wrong.
Possible culprits are:
Missing bytes at the end
converted bytes
messed up order of bytes
I'd expect looking at the first 10, the last 10 and the total number of bytes should be sufficient to give you a good idea what is going on.

Writing Video Files in Java

I'm trying to find a way to save a video file. Initially I'd put the video files as blob data into a database, and now, I'm trying to get the blob data back, convert it into bytes, and then write it to a new file. I've been successful in doing this, but the problem is, I can't make the resulting files to run. I tried storing, retrieving, and writing .flv and .mp4 files, but neither work :/ Can anyone help me? Much appreciated! :)
Here is my code: :)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root","password");
Statement st1 = (Statement) con.createStatement();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = con.prepareStatement("SELECT video_file from video where video_id = " + video_id);
rs = pstmt.executeQuery();
Blob blob = null;
byte[] blyte = null;
if(rs.next()) {
blob = rs.getBlob("video_file");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("C:\\Downloads\\file2.mp4");
int b = 0;
while(b != -1){
fos.write(b);
b = bis.read();
}
}
//exceptions beyond this point
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
There is a '\0' byte written to fos in first iteration of the while-loop which does not come from bis.read().

Categories

Resources