I'm trying to send bmp image using socket. I have such code on android:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
MainActivity.bmp.compress(Bitmap.CompressFormat.JPEG, 20,
stream);
byte[] byteArray = stream.toByteArray();
OutputStream os = echoSocket.getOutputStream();
os.write(byteArray,0,byteArray.length);
os.flush();
and on PC:
String q = SockIn.readLine();
File file = new File("filename.bmp");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(q);
in bmp file I only get up to 401 bytes, which of course is corrupt bmp image. what am I doing wrong?
MODIFIED
modified PC side, now the code is:
InputStream in_ = clientSocket.getInputStream();
OutputStream out_ = new FileOutputStream("filename.bmp");
final byte[] buffer = new byte[1024];
int read = -1;
int i = 0;
while ((read = in_.read(buffer)) != -1) {
out_.write(buffer, 0, read);
System.out.println(i);
i++;
}
in_.close();
out_.close();
System.out.println("Done");
It never gets to last line( println("Done") ). when I close android program, it gets to last line and bmp opens succesfully
Your reading logic is completely off. You only use a readLine() once and then write that to file. The data that was written to the socket on the device side was binary. That means that trying to read it as if it were textual (as readLine() does) will return meaningless junk. The reason it's usually 401 bytes long is that readLine() will look for the first newline character combination and return everything up to that as a String. This is not what you want.
What you need is a loop that will read from the socket and write into the file as long as there is data in the socket. A standard copy loop should suffice here.
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream(...);
final byte[] buffer = new byte[BUFFER_SIZE];
int read = -1;
while ((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
in.close();
out.close();
Note that the above code isn't tested but something to that effect should do the trick.
Why are you reading a String if you are sending a byte ?
Try those setp one by one only if the previous did not worked.
1. Read() and don't Readline() what you are writing
If you write a byte, read a byte
Byte obj = SockIn.read();
2. Encode your array before sending
Base64.encodeBase64String(byteArray);
Related
I am creating an app that helps user to hide secret files like text file or photos. If user is going to delete the secret files, I want to make sure the files deleted is unrecoverable. I am trying to write zero byte or zero write the file before deleting. The problem is it doesn't zero write the file, it doesn't do anything. This is what I currently have.
public void zeroWriteDelete(File file) throws IOException{
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream1 = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
int read;
while((read = fileInputStream.read(buffer)) > 0){
Arrays.fill(buffer, (byte)0);
fileOutputStream1.write(buffer, 0, read);
}
fileOutputStream1.flush();
fileOutputStream1.close();
fileInputStream.close();
}
So, how do I zero write or overwrite the file with zero byte or data ? Or maybe other ways to make sure the deleted file is unrecoverable ?
You don't need to read from the file, or zero the buffer:
public void zeroWriteDelete(File file) throws IOException{
long length = file.length();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
byte[] buffer = new byte[4 * 1024];
for (long i = 0; i < length; i += buffer.length) {
raf.write(buffer, 0, (int)Math.min(buffer.length, length-i));
}
raf.close();
file.delete(); // you forgot this rather vital part
}
E&OE
This question already has answers here:
Convert InputStream to byte array in Java
(34 answers)
Closed 5 years ago.
Trying to get bytes data from inputstream as shown in the below code. But, the bytes variable is null. What might be the reason? FYI- Image is available in the given uri, as i can see the image in imageView1. (Testing on Lollipop).
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
var_Bitmap = BitmapFactory.decodeStream(imageStream);
ImageView imageView1 = (ImageView) findViewById(R.id.ui_imageView_browse);
imageView1.setImageBitmap(var_Bitmap);
byte[] bytes = IOUtils.toByteArray(imageStream);
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"master"+File.separator);
createDir.mkdir();
File file = new File(root + "master" + File.separator +"master.jpg");
path=root+"master"+File.separator+"master.jpg";
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
As pskink suggested in a comment, the issue was that the input stream has been read to the EOF by decodeStream, so there is nothing more to read.
To solve the problem, I created a temporary variable for inputstream.
Try this :
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Hope it helps.
I need to develop an application to transfer image continuously from android to android which should be received as an video on the client side..and i have two applications which one (server) will send the file through socket connected by wifi and other should the client side should recive the image which is sent...currently am just saving it in one location in the client side...am able to receive the file correctly...but the problem is am not able to send all files correctly all the time...
Means some time the image file will be transfered and some time i ll not be able to receive and when i ll not be able to receive i am getting an exception as
: java.io.UTFDataFormatException: ...and the file is not written and saved on the receiving side...
If am not able to receive images continuously...i can think there is some problem in the code..but am able to transfer it some times..and some time not able to transfer...am not able to figure what the issue is...plz any guidance
the error is:
11-18 10:38:17.351: W/System.err(1001): java.io.UTFDataFormatException: bad second or third byte at 2
11-18 10:38:17.359: W/System.err(1001): at java.nio.charset.ModifiedUtf8.decode(ModifiedUtf8.java:53)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:444)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.decodeUTF(DataInputStream.java:438)
11-18 10:38:17.359: W/System.err(1001): at java.io.DataInputStream.readUTF(DataInputStream.java:433)
and the file is not saved when i get this exception..
Many scenarios i have tested by capturing image and saving and sending...and also compressing the image and sending...in these scenarios some very rarely it is going....am not able to figure out it...
Sender code:
File myFile = new File(sdCard+"/image/image.jpg");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
tv.setText("Send file name size to server");
//Sending file name,file size and to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
socket.close();
tv.setText("Socket Close");
tv.setText("Sent");
Receiver Code:
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
String fileName = clientData.readUTF();
File file = new File(dir,fileName);
OutputStream output = new FileOutputStream(file);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
System.out.println("Writing");
}
// status.setText("Received");
// Closing the FileOutputStream handle
output.close();
s.close();
Thanks and Regards,
Divya.K
I was stuck on this thing i combined few days of my search and reached to this... Try it and see if works for you..
Bitmap myBitmap = null;
try {
File imgFile = new File(imgPath);
if (imgFile.exists()) {
File image = new File(imgPath, "imagename.jpg");
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
//myBitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true); //uncomment this if you want to scale the image
//imageView.setImageBitmap(bitmap);//to set bitmap to image view
}
Socket sock = new Socket("192.168.1.1", 80);//ip adress and port number
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (myBitmap != null) {
myBitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
}
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
BufferedInputStream bis = new BufferedInputStream(bs);
bis.read(bitmapdata, 0, bitmapdata.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(bitmapdata, 0, bitmapdata.length);
os.flush();
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm trying to send bmp image using socket. I have such code on android:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
MainActivity.bmp.compress(Bitmap.CompressFormat.JPEG, 20,
stream);
byte[] byteArray = stream.toByteArray();
OutputStream os = echoSocket.getOutputStream();
os.write(byteArray,0,byteArray.length);
os.flush();
and on PC:
InputStream in_ = clientSocket.getInputStream();
OutputStream out_ = new FileOutputStream("filename.bmp");
final byte[] buffer = new byte[1024];
int read = -1;
int i = 0;
while ((read = in_.read(buffer)) != -1) {
out_.write(buffer, 0, read);
System.out.println(i);
i++;
}
in_.close();
out_.close();
System.out.println("Done");
It never gets to last line( println("Done") ). It only does when I close android program, it gets to last line and bmp opens succesfully. problem is in_.read waits after android has finished transmitting, and i can't make it work.
You never close the socket/OutputStream on the device side so the PC side doesn't know that there is no more data and so it just spins in the while loop reading 0 bytes at a time.
Also, if you're going to use my solution, please mark me as the accepted answer in your previous thread.
So, I have a simple Android app that connects to a Java Server application using Sockets.
Specifically, I want to be able to send a file from the Server application to the Android app and then store that file in internal memory on the device.
The basis of the server code for transferring the file is:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(System.getProperty("user.home"), "text.txt")));
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
bos.flush();
bos.close();
and the Client code to receive the file is as follows:
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(openFileOutput("text.txt", Context.MODE_PRIVATE));
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
bos.flush();
bos.close();
The code appears to work fine when the client code is in a standard Java application, that is, the file sends successfully from server to client.
The problem arises when I use this code in an Android app. (Note: I use a standard FileOutputStream in the standard Java app instead of the
openFileOutput("text.txt", Context.MODE_PRIVATE))
line above).
For example purposes, the file I am transferring is a simple UTF-8 text file, which contains a single string
This is a text file.
However, when I pull this file I have copied to the emulator, from the "/data/data//files" folder on the emulator, there are an extra couple of bytes at the top of the file so the content is now
¨ÌThis is a text file.
I have no idea why this is happening and it has me stumped. I think the problem might be related to the line:
BufferedOutputStream bos = new BufferedOutputStream(openFileOutput("text.txt", Context.MODE_PRIVATE));
but I can't quite figure it out.
Any suggestions as to what I am doing wrong would be most helpful.
Thank you in advance