PDF to Bytearray conversion in java - java

Below is my code to convert a PDF file to byte array
public class ByteArrayExample{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name: ");
String str = bf.readLine();
File file = new File(str);
//File length
int size = (int)file.length();
if (size > Integer.MAX_VALUE){
System.out.println("File is to larger");
}
byte[] bytes = new byte[size];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int read = 0;
int numRead = 0;
while (read < bytes.length && (numRead=dis.read(bytes, read,
bytes.length-read)) >= 0) {
read = read + numRead;
}
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: "+file.getName());
}
}
catch (Exception e){
e.getMessage();
}
}
}
Issue is this actually converts the file name into the byte array not the actual PDF file.Can anyone please help me with this.

I added this to the end to check it and it copied the PDF file. Your code is working fine
dis.close();
DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
out.write(bytes);
out.close();
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: "+file.getName());
}
edit: here is my entire code, its just copied from yours. I ran it in IDE (eclipse) and entered "c:\mypdf.pdf" for the input and it copied it to out.pdf. Identical Copys. Do note that I did close both streams which I noticed you forgot to do in your code.
public class Main {
public static void main(String[] args) {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name: ");
String str = bf.readLine();
File file = new File(str);
//File length
int size = (int) file.length();
if (size > Integer.MAX_VALUE) {
System.out.println("File is to larger");
}
byte[] bytes = new byte[size];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int read = 0;
int numRead = 0;
while (read < bytes.length && (numRead = dis.read(bytes, read,
bytes.length - read)) >= 0) {
read = read + numRead;
}
dis.close();
DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
out.write(bytes);
out.close();
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: " + file.getName());
}
} catch (Exception e) {
e.getMessage();
}
}
}

Related

Java socket getting only NUL characters after writing byte array

I'm trying to send files in chunks from a client to server via byte arrays. I'm using ObjectInputStream. The write works and the filesize matches but when I open the file, I only get a blank textfile(which when opened in a IDE, shows NUL,NUL,NUL...).
Server code:
try(
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
){
byte[] arr = new byte[chunkSize];
try {
int len = 0;
long bytesRead = 0;
byte[] bytes = new byte[chunkSize];
int chunkNo = 1;
while(true)
{
len = in.read(bytes,0, chunkSize);
System.out.println();
if(len < 0)
break;
fileOut.write(arr, 0, len);
bytesRead += len;
out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
String ackReply = (String) in.readObject();
if(ackReply.equalsIgnoreCase((Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG))){
if(Server.DEBUG)
System.out.println(fileName + " send timeout.");
deleteFile();
break;
}else if (ackReply.equalsIgnoreCase(Server.UPLOAD_COMPLETE_MSG)){
if(bytesRead != fileSize){
System.out.println(fileName + " File size mismatch");
deleteFile();
break;
}else{
System.out.println( fileName + " File written");
break;
}
}
}
}catch (IOException ioe){
if(Server.DEBUG)
ioe.printStackTrace();
}
Client code:
try(
FileInputStream fileInput = new FileInputStream(file);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
){
byte[] arr = new byte[chunkSize];
try {
int len = 0;
int bytesRead = 0;
int chunkCount = 1;
while((len = fileInput.read(arr, 0, chunkSize)) != -1)
{
out.write(arr, 0, len);
out.flush();
bytesRead += len;
}
try {
System.out.println("wait ack");
socket.setSoTimeout(timeout);
String ack = (String) in.readObject();
System.out.println(ack);
if(bytesRead >= fileSize){
out.writeObject(Server.UPLOAD_COMPLETE_MSG);
System.out.println(Server.UPLOAD_COMPLETE_MSG);
break;
}else{
out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
}
}catch (SocketTimeoutException e){
out.writeObject(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);
System.out.println(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);
break;
}finally {
socket.setSoTimeout(0);
}
}
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}catch (FileNotFoundException fnfe){
System.out.println("No such file: " + fileName);
}catch (Exception e){
e.printStackTrace();
}
finally {
try {
socket.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
I tried writing the byte array to another file on the client side and the copy was identical. So the problem must be during sending data over socket.
The Server.X_MSG is just a constant string. I don't know if mixing readobject() and read(bytearray) on the same ObjectInputStream causes any issues though.
Maybe it's because fileOut.write(arr, 0, len); use arr and len = in.read(bytes,0, chunkSize); use bytes? They are not the same array.

Handle specific byte from socket in Java

I'm using the code below to read a Unix socket:
Boolean flag = false;
while (!flag) {
try {
File socketFile = new File("./RISP");
AFUNIXSocket sock = AFUNIXSocket.newInstance();
sock.connect(new AFUNIXSocketAddress(socketFile));
System.out.println("!!!!!!!!!!CONNECTED!!!!!!!!!");
flag = true;
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line = null;
while ((line = input.readLine())!=null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("NOT CONNECTED....." + e);
}
try {
Thread.sleep(2000);
} catch (InterruptedException inter) {
System.out.println(inter);
}
}
I need to read the first 4 bytes of each pack and convert them from binary to integer.
I've read many posts but I'm still looking for the best solution to my problem.
Reader and Writer are designed for reading text.
For binary, you should try InputStream and OutputStream, in this case, you want DataInputStream, possibly buffered.
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
int len = in.readInt(); // read big-endian.
if (LITTLE_ENDIAN)
len = Integer.reverseBytes(len);
byte[] bytes = new byte[len];
in.readFully(bytes);
seems it works
DataInputStream in = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
int len = -1;
while ((len = in.readInt()) != -1) {
len = Integer.reverseBytes(len);
byte[] bytes = new byte[len];
in.readFully(bytes);
if (bytes.length > 4) {
System.out.println(" BYTE0: " + bytes[0] +
" BYTE1: " + bytes[1] +
" BYTE2: " + bytes[2] +
" BYTE2: " + bytes[3] +
" LENGHT: " + bytes.length);
}
}
please let me know is i miss something.
thanks a lot to you guys.

Reading JPEG Stream over socket gives Null characters

I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.
while ((ret = input.read(imageCharArray)) != -1) {
packet.append(new String(imageCharArray, 0, ret));
totRead += ret;
imageCharArray = new char[4096];
}
file = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
PrintWriter printWriter = new PrintWriter(file);
// outputStream = new FileOutputStream(file); //also Used FileoutputStream for writting
// outputStream.write(packet.toString().getBytes());//
// ,
printWriter.write(packet.toString());
// outputStream.close();
printWriter.close();
}
I have also tried FileoutputStream but hardlucj for this too as commented in my code.
Edit
I have used this also. I have a content length field upto which i am reading and writing
byte[] bytes = new byte[1024];
int totalReadLength = 0;
// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
&& contentLength >= (totalReadLength)) {
outputStream.write(bytes, 0, read);
totalReadLength += read;
System.out.println(" read size ======= "
+ read + " totalReadLength = "
+ totalReadLength);
}
String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
total += count;
out.write(buffer, 0, count);
}
I tested it in my Nexus4 and it's working for me. Here is the snippet of code what I tried :
public void saveImage(String urlPath)throws Exception{
String fileName = "kumar.jpg";
File folder = new File("/sdcard/MyImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder,
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just Call the above function in a background thread and pass your url. It'll work for sure. Let me know if it helps.
You can check below code.
destinationFile = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[1024];
int i;
for (long l = 0L; (i = input.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();

Why doesn't it read the line-termination ''\n'

This code is trying to read a file then reverse it to an output file.
When it writes it (without reversing) the output is the same.
But when it is reversed the output is written ALL on ONE line in the output file.
int i;
int x = 0;
int[] ar = new int[9999];
BufferedInputStream fin;
BufferedOutputStream fout;
try {
File f1 = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt");
File f2 = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt");
fin = new BufferedInputStream(new FileInputStream(f1));
fout = new BufferedOutputStream(new FileOutputStream(f2));
while ((i = fin.read()) != -1) { //reads file into an array
ar[x] = i;
x++;
}
for(int y = (x-1); y >= 0; y--){
//writes to a file from the end of the array
fout.write(ar[y]);
}
System.out.println();
fin.close();
fout.close();
} catch (FileNotFoundException e) {
System.out.println("File is NOT found.");
}
I'm using BufferedInputStream and BufferedOutputStream
Probably you are reading \r\n and writing back \n\r.
You have to handle \r\n as a separate entity.

Joining two mp3 files into one

I have this code to read bytes to another file.
But I'm not able to concatenate two mp3 files into one.
Am I missing something?
public static void main(String[] args) {
String strFileName = ("D:/Music/Assb/Love.mp3");
BufferedOutputStream bos = null;
try
{
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(strFileName));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
/*
* To write byte array to file use,
* public void write(byte[] b) method of BufferedOutputStream
* class.
*/
System.out.println("Writing byte array to file");
bos.write(str.getBytes());
System.out.println("File written");
It`s suck. Mp3 file starts with headers. For correct merging you have to skip first 32 bytes. Try this.
try {
FileInputStream fistream1 = new FileInputStream(_file_name);
File f = new File(new File(_file_name).getParent()+"/final.mp3");
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream sistream = new FileOutputStream((new File(_file_name)).getParent()+"/final.mp3");
int temp;
int size = 0;
temp = fistream1.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream1.read();
};
fistream1.close();
FileInputStream fistream2 = new FileInputStream(temp_file);
fistream2.read(new byte[32],0,32);
temp = fistream2.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream2.read();
};
fistream2.close();
sistream.close();
} catch (IOException e) {
e.printStackTrace();
}
You need to do this in two steps
String str = "D:/Music/Assembled/Heart001.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
str = "D:/Music/Assembled/Heart002.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
And as you can see you need code to open the mp3 file to read it
What Are You Trying For...Actually..if You Want To Read 2 Files to Byte Stream the dont String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
make str1=D:/Music/Assembled/Heart001.mp3 and str2=D:/Music/Assembled/Heart002.mp3 and read str1,str2 seperately through bufferedoutputsream
This code will work well and merge audio of similar type with in seconds...
try {
InputStream in = new FileInputStream("C:\\a.mp3");//firstmp3
byte[] buffer = new byte[1 << 20]; // loads 1 MB of the file
OutputStream os = new FileOutputStream(new File("C:\\output.mp3", true);//output mp3
int count;
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
in = new FileInputStream("C:\\b.mp3");//second mp3
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources