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())
Related
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()
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 want to bundle an image with my application. I am planing to keep the image in the drawable or the raw folder. I wanted to know how to make a File object of this image?
Something like this:
File file = new File("fileurl");
Thank you.
Can you please try this one ?
try {
File mFile=new File("my file name");
InputStream inputStream = getResources().openRawResource(R.drawable.ic_launcher);
OutputStream out=new FileOutputStream(mFile);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
Hope this will help you.
If you put your image resource inside your Raw folder within your workspace, you can access it inside your class by using :
getResources.openRawResources(R.raw.resource_id)
EDIT :
the above code will return an inputStream, to convert it to file, try this one :
inputStream = getResources.openRawResources(R.raw.resource_id)`
// write the inputStream to a FileOutputStream
File file = new File("fileurl");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
I have a png file in the raw folder. I get the inputStream using :
inputStream = getResources().openRawResource(R.raw.test);
I am trying to write this inputStream in a new file in an Android application. This is my code:
inputStream = getResources().openRawResource(R.raw.test);
File file = new File("/test.png");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024*1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
When I run the application, I get the following error in the logcat:
java.io.FileNotFoundException: /test.png: open failed: EROFS (Read-only file system)
Basically I want to create a File object so that I can send this to my server.
Thank you.
You will not have access to the file-system root, which is what you're attempting to access. For your purposes, you can write to internal files new File("test.png"), which places the file in the application-internal storage -- better yet, access it explicitly using getFilesDir().
For truly temporary files, you might want to look into getCacheDir() -- should you forget to delete those temporary files, the system will reclaim the space when it runs out of room.
Here's my solution:
inputStream = getResources().openRawResource(R.raw.earth);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
file.createNewFile();
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024*1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();
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.