How to retrieve an zip file from oracle blob using java? - java

I have an zip file stored in an Oracle database table which is consisting of three different xml files. What I'm trying to do is get this zip file in my local file system. To retrieve this zip file I have written below java code:
package com.pack.IOT;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test2 {
public static Connection con;
public static PreparedStatement stmt;
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,uname,pwd);
stmt=con.prepareStatement("select * from FileStore");
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
InputStream is = rs.getBinaryStream(3);
convert(is);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void convert(InputStream is) {
FileOutputStream outputStream = null;
File file = new File("C:\\Users\\nshaik\\Desktop\\IOTZip.zip");
try {
outputStream = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result;
result = bis.read();
while (result != -1) {
buf.write((byte) result);
result = bis.read();
}
outputStream.write(buf.toByteArray());
System.out.println("File write success....");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code is running fine, but I'm seeing an error "Unexpected end of archive", and this zip file should contain three different files, but I see only one file and it has a size of zero.
I'm not sure what I'm doing wrong, anyone's help would be really appreciated.

Below is the working code for above requirement,
package com.pack.IOT;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test2 {
public static Connection con;
public static PreparedStatement stmt;
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,uname,pwd);
stmt=con.prepareStatement("select * from FileStore");
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
InputStream is = rs.getBinaryStream(3);
convert(is);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void convert(InputStream is) {
FileOutputStream outputStream = null;
File file = new File("C:\\Users\\nshaik\\Desktop\\IOTZip.zip");
try {
outputStream = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result;
result = bis.read();
while (result != -1) {
buf.write((byte) result);
result = bis.read();
}
outputStream.write(buf.toByteArray());
System.out.println("File write success....");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

Related

Download blob data in a zip file in a simple java program

I'm not able to download the files using the below code as i have multiple types of extensions to download and i want to zip all the files and download. If i run the below code, it says files is corrupted. someone please help on this?
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcReadFile {
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
String url = "jdbc:oracle:thin:#xxx:xxxx:xxx";
String user = "xxx";
String password = "xxx";
String filePath = "C:/abc.vsd";
try {
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT DOC_BO FROM table fetch first 10 rows only";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("DOC_BO");
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File saved");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
No front end is required for this. Issue is resolved using the below code.
public class BlobDataExtract {
static ZipOutputStream zos = null;
static String url = "jdbc:oracle:thin:#hostname:1521:SID";
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql = "select Blob_Data,ORIG_NM from table";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
byte[] docBlob = null;
String filename = null;
FileOutputStream fos = new FileOutputStream("C:/Users/test.zip");
zos = new ZipOutputStream(fos);
while (rs.next()) {
docBlob = rs.getBytes("Blob_Data");
filename = rs.getString("ORIG_NM");
try {
zos.putNextEntry(new ZipEntry(filename));
zos.write(docBlob, 0, docBlob.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
}
}

Java: Multi line output via Socket

i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}

PDF file corrupted after downloading from mysql java

I am trying to upload a pdf file to my database and trying to download same file but I am unable to open the file after it's downloaded I get an error stating file type not supported.
Here is the code for file Upload.
package itext;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
public class FileUpload {
public static void fileupload() throws FileNotFoundException{
String inFile="D:/Eclipse Java/myown.pdf";
FileInputStream io = new FileInputStream(inFile);
byte[] pdfData = new byte[(int) inFile.length()];
DataInputStream dis;
try {
dis = new DataInputStream(new FileInputStream(inFile));
dis.readFully(pdfData); // read from file into byte[] array
dis.close();
Connection dbConnection;
String myConnectionString =
"jdbc:mysql://******/*****";
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps = (PreparedStatement) dbConnection.prepareStatement("INSERT INTO Form_BL (AppID,Form) VALUES (?,?)");
ps.setString(1, "1");
ps.setBytes(2, pdfData); // byte[] array
ps.executeUpdate();
ps.setBinaryStream(1, (InputStream)dis,(int)inFile.length());
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the code for downloading
package itext;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.PreparedStatement;
public class FileDownload {
public static void filedownload(){
Connection dbConnection;
ResultSet rs;
String myConnectionString =
"jdbc:mysql://*****/*****";
try {
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps=(PreparedStatement) dbConnection.prepareStatement("select AppID from Form_BL where AppID='1' ");
rs=ps.executeQuery();
rs.next();
java.sql.Blob b=rs.getBlob(1);
byte barr[]=new byte[(int)b.length()];//an array is created but contains no data
barr=b.getBytes(1,(int)b.length());
FileOutputStream fout=new FileOutputStream("D:/download.pdf");
fout.write(barr);
fout.close();
System.out.println("ok");
dbConnection.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I was using the reference of the following link for this operation.
Upload PDF file to mysql BLOB by using java.sql.PreparedStatement without corruption. Thanks in advance
It looks like the code to save the binary content (PDF file) into a BLOB is fine. But when you try to get the PDF content back it looks like you have some trouble.
You might wan to try this:
Blob b = rs.getBlob(1);
InputStream is = b.getBinaryStream();
FileOutputStream fos = new FileOutputStream("D:/download.pdf");
int i = 0;
// IMPORTANT: Remember to handle/close all I/O properly
while ((i = is.read()) != -1) {
fos.write(b);
}

Java download textfile from FTP empty textfile

Hi I'm trying to get my program to download a text document from my FTP server.
This is the code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
public class NetTestFTP {
public static void main(String[] args) {
FTPClient client = new FTPClient();
OutputStream outStream;
try {
client.connect("82.44.221.198");
client.login("User", "Pass");
String remoteFile = "/hello.txt";
outStream = new FileOutputStream("hello.txt");
client.retrieveFile(remoteFile, outStream);
} catch (IOException ioe) {
System.out.println("Error communicating with FTP server.");
} finally {
try {
client.disconnect();
} catch (IOException e) {
System.out.println("Problem disconnecting from FTP server");
}
}
}
}

My Server and Client socket program just hangs without printing anything

Why does nothing get printed out to the console?
I have a server socket which starts a new thread for each client. It reads a line from the client outputs it and sends a response of its own. This is printed on the client side. Here's the code:
The client code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
PrintWriter out = null;
BufferedReader in = null;
Socket echoSocket=null;
try {
echoSocket = new Socket("localhost", 8999);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
for(int i=0;i<20;i++) {
out.print("Sending to Server"+i);
System.out.println("Received from Server"+in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
try {
in.close();
} finally {
try {
out.close();
} finally {
echoSocket.close();
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
The server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
/**
* #param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(8999);
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
while (true) {
try {
final Socket sock = server.accept();
threadPool.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
BufferedReader br = null;
PrintWriter out = null;
try {
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
for (int i = 0; i < 20; i++) {
String readLine = br.readLine();
System.out.println(readLine);
out.print(readLine + "response");
}
} finally {
try {
br.close();
} finally {
try {
out.close();
} finally {
sock.close();
}
}
}
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Well for one, you should probably println instead of print on your writers (in both client and server).

Categories

Resources