I am trying to read InputStream after writing output stream to sdcard. I have downloaded file from HttpURLConnection. File is successfuly written to sdcard. But I am trying to read inputstream from same file but contents are not being read properly. On emulator some contents are shown but on actual device contents are not shown. Can you please help what can be the issue? I am posting downloading, writing and reading code.
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();
/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);
int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();
File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);
inputStream.available() is only an estimate not actual length of the complete input data.
FileInputStream.available()
Related
I'm facing an issue writing PDF file to BluetoothSocket OutputStream in my android project. Text file write(print) is working fine but when I'm writing PDF file, it prints out some gibberish text not the data inside the PDF file. Here is my code snippet:
File file = new File("/storage/emulated/0/Download/sample.pdf");
inputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
int nextByte;
while ((nextByte = inputStream.read(bytes, 0, bytes.length)) != -1) {
outputStream.write(bytes, 0, nextByte);
outputStream.flush();
}
inputStream.close();
outputStream.close();
Here outputStream is BluetoothSocket OutputStream.(ex: bluetoothSocket.getOutputStream())
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();
}
simply i need to download an image but the problem is the image get corrupted !!!
i find many way to download the image but still this problem appeared .
i try do this :
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file2 = new File(path,"DemoPictureX.png");
InputStream is=(InputStream) new URL("http://androidsaveitem.appspot.com/downloadjpg").getContent();
OutputStream os = new FileOutputStream(file2);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
i think it read just read some row from the image !!!
you need a loop and read with a smaller buffer (like 1024 bytes) from the stream.
URL url = new URL("your url here");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(targetFile);
byte buffer[] = new byte[1024];
int read;
while ((read = bis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
bis.close();
is.close();
This should work for you
i am trying to download files using getFileStream() in dropbox api but it returns file
information only,please help me to download file data.
here is code..
FileDownload fd = api.getFileStream("dropbox","/public/myfilename.rtf", null);
BufferedReader br = new BufferedReader(new InputStreamReader(fd.is));
BufferedWriter bw = new BufferedWriter(new FileWriter(newfile));
char[] buffer = new char[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break
}
bw.write(buffer, 0, read);
}
FileDownload fd = api.getFileStream("dropbox",path, null);
File f=new File("/sdcard/test.pdf");
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=fd.is.read(buf))>0)
out.write(buf,0,len);
out.close();
fd.is.close();
and mention your path like "/public/myfilename"
Here in my code i want to save it as a PDF so
i am creating one pdf and writing data to that.