I am reading the blob data from Oracle database & writing it to a text file. I have two column in my database called Number & system. I have 100 counts in my table. But only the last row is writing in my text row. below is the code I have tried.
rs =stmt.executeQuery("select Number, system from system");
Blob lob = null;
while (rs.next()) {
String RECID = rs.getString(1);
System.out.println("Number"+ Number);
lob=rs.getBlob("system");
byte[] bdata = lob.getBytes(1, (int) lob.length());
String text = new String(bdata);
System.out.println("text"+ text);
System.out.println("rs value"+ lob);
String test=null;
test=RECID+":"+text;
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeBytes(test);
dos.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
In text file i am getting 100th record only other 99 rows are not writing.
You are replacing existing text each time in your while loop.
Try this:
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
DataOutputStream dos = new DataOutputStream(fos);
while (rs.next()) {
String RECID = rs.getString(1);
System.out.println("Number"+ Number);
lob=rs.getBlob("system");
byte[] bdata = lob.getBytes(1, (int) lob.length());
String text = new String(bdata);
System.out.println("text"+ text);
System.out.println("rs value"+ lob);
String test=null;
test=RECID+":"+text;
dos.writeBytes(test+"\n");
}
dos.close();
Replace the line in your code
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt");
With:
FileOutputStream fos = new FileOutputStream("C:/DataRead/system.txt", true);
Related
Hi i am trying to read an ArrayList of Integer and get EOFException.
i have a ArrayList of Question which is serialized and i do the same thing for reading it no problem, but with ArrayList Integer dont work.
i write the two ArrayList like so: (im ommiting all the other fields that are not relevant)
String sqlQuery = "insert into test values (?,?,?,?,?,?,?,?,?)";
PreparedStatement pst = null;
try {
if (DBConnector.myConn != null) {
pst = DBConnector.myConn.prepareStatement(sqlQuery);
// serialize object
Blob questionsBlob = DBConnector.myConn.createBlob();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(t.getQuestions());
oos.close();
Blob pointsBlob = DBConnector.myConn.createBlob();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
ObjectOutputStream oos2 = new ObjectOutputStream(baos2);
oos.writeObject(t.getPointsPerQuestion());
oos2.close();
// store in byte array
byte[] questionsAsByte = baos.toByteArray();
byte[] pointsAsByte = baos2.toByteArray();
// fill blob object with byte array
questionsBlob.setBytes(1, questionsAsByte);
pointsBlob.setBytes(1, pointsAsByte);
pst.setBlob(3, questionsBlob);
pst.setBlob(4, pointsBlob);
pst.executeUpdate();
and read the objects:
String sqlQuery = "select * from test where teacherUsername = \"" + username + "\";";
ArrayList<Test> arr = new ArrayList<Test>();
ArrayList<Question> questions;
ArrayList<Integer> points;
try {
if (DBConnector.myConn != null) {
Statement st = DBConnector.myConn.createStatement();
ResultSet rs = st.executeQuery(sqlQuery);
while (rs.next()) {
questions = new ArrayList<>();
points = new ArrayList<>();
Blob questionsBlob = rs.getBlob(3);
BufferedInputStream bis = new BufferedInputStream(questionsBlob.getBinaryStream());
ObjectInputStream ois = new ObjectInputStream(bis);
questions = (ArrayList<Question>) ois.readObject();
System.out.println(questions);
Blob qPointsBlob = rs.getBlob(4);
BufferedInputStream bis1 = new BufferedInputStream(qPointsBlob.getBinaryStream());
ObjectInputStream ois1 = new ObjectInputStream(bis1);
try {
points = (ArrayList<Integer>) ois1.readObject(); // PROBLEM HERE
}catch(EOFException e) {
System.out.println(points);
}
when i try to read the data - it works with the ArrayList of Question and really shows me the questions, but with the ArrayList of Integer it gives me the EOFException.
any ideas ?
I am trying to save images in MySQL database from a Java swing application. I am using JFileChsoser to get the path of the image. Then after that converting the file so that it can be saved in the MySQL column which is of BLOB type. But every image I try to save does not save properly or get converted properly. Could someone tell me what I'm doing wrong over here?
private void btn_choosepicActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser picchooser = new JFileChooser();
picchooser.setDialogTitle("Select Image");
picchooser.showOpenDialog(null);
File pic=picchooser.getSelectedFile();
path= pic.getAbsolutePath();
txt_path.setText(path.replace('\\','/'));
try{
File image = new File(path);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream baos= new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for(int readNum; (readNum=fis.read(buff)) !=-1 ; ){
baos.write(buff,0,readNum);
}
userimage=baos.toByteArray();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
And then after this Im saving it to the database like so.
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
String user= txt_username.getText();
try{
String sql="insert into imgtst (username,image) values ('"+user+"','"+userimage+"')";
pst=con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
and I have declared the variable userimage and path as a global variables
String path=null;
byte[] userimage=null;
You are converting the byte[] to a String in your sql statement, and you will end up with incorrect data.
The right way to use a BLOB would be to pass the InputStream itself. You can use the FileInputStream you are using to read the file.
File image = new File(path);
FileInputStream fis = new FileInputStream ( image );
String sql="insert into imgtst (username,image) values (?, ?)";
pst=con.prepareStatement(sql);
pst.setString(1, user);
pst.setBinaryStream (2, fis, (int) file.length() );
When you retrieve it back you can similarly get an InputStream from the ResultSet:
InputStream imgStream = resultSet.getBinaryStream(2);
In jsp i get file from BD and want to download it on client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
byte[] file = rs.getBytes("files");
fileName=rs.getString("filename");
}
FileOutputStream fs = new FileOutputStream(new File(fileName));
BufferedOutputStream bs = new BufferedOutputStream(fs);
bs.write(file);
bs.close();
fs.close();
rs.close();
ps.close();
%>
I will PDF file. So i have some questions:
1. What i gonna do with file to send it to JavaScript.
2. Can i save this file using ExtJs 3.4 or JavaScript?
UPDATE
Now i try to send file from server to client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
byte[] file=null;
int bufferSize = 8192;
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
file = rs.getBytes("files");
fileName=rs.getString("filename");
}
File dFile=new File(fileName);
InputStream in1 = request.getInputStream();
int read;
while ((read = in1.read(file, 0, bufferSize)) != -1) {
out.write(file, 0, read);
}
sta.close();
rs.close();
conn.close();
%>
But get error:
The method write(char[], int, int) in the type Writer is not applicable for the arguments (byte[], int, int)
So how to do it?
UPDATE2
Using this code i dont get any errors but in firebug i see that server nothing send to client:
<%
String num = request.getParameter("param");
Statement sta = null;
sta = conn.createStatement();
String fileName="";
byte[] file=null;
int bufferSize = 8192;
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
file = rs.getBytes("files");
fileName=rs.getString("filename");
}
//File dFile=new File(fileName);
FileOutputStream fout = fout = new FileOutputStream(fileName);
//BufferedInputStream in1 = new BufferedInputStream(fout);
InputStream in1 = request.getInputStream();
int read;
while ((read = in1.read(file, 0, bufferSize)) != -1) {
fout.write(file, 0, read);
}
sta.close();
rs.close();
conn.close();
%>
You have simply to create a Download URL with a Content-Disposition Header.
Now the bad/good news (It depends on the point of view). You can not store a file through JavaScript onto a users-filesystem (expect the new File-API). But this will sandbox your filesystem. So you can't make the browser store that file onto a certain path.
I wrote some code that lets me save pictures in my data/data in Android internal storage. Now I would like to know if there is a way to delete those pictures from internal storage.
Here is what I have for saving:
public boolean saveImg( String showId ) {
try {
URL url = new URL(getImgUrl( showId ));
File file = new File(showId + ".jpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
//Define InputStreams to read from the URLConnection.
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//Read bytes to the Buffer until there is nothing more to read(-1).
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
//Convert the Bytes read to a String.
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
return true;
} catch (IOException e) {
return false;
}
}
I tried this but it doesn't delete from data/data. Any suggestions as to what I'm doing wrong?
public void DeleteImg(String showId) {
File file = new File( PATH + showId +".jpg" );
file.delete();
}
Try this:
File file = new File(selectedFilePath);
boolean deleted = file.delete();
From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
One can utilize the autoclosable interface that was introduced in java 7.
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
Read from file or string to bytearray.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}