I've made I simple function to write from URL to file. Everything works good until out.write(), I mean there's no exception, but it just doesn't write anything to file
Here's code
private boolean getText(String url, String name) throws IOException {
if(url!=null){
FileWriter fstream = new FileWriter(PATH+"/"+name+".txt");
BufferedWriter out = new BufferedWriter(fstream);
URL _url = new URL(url);
int code = ((HttpURLConnection) _url.openConnection()).getResponseCode();
if(code==200){
URLConnection urlConnection = _url.openConnection(); //
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
out.write(chunk);
}
return true;
}
out.close();
}
return false;
}
Can someone tell me what's wrong please?
Try fstream.flush().
Also out.close() should be called before returning from a function.
Related
I need to pass an image in application/octet-stream format. I think it means binary image data. How can I convert my drawable to this format?
Here is the code where I'll pass this data in the place of body :
StringEntity reqEntity = new StringEntity("{body}");
You can use HttpURLConnection, something like this:
Long BUFFER_SIZE = 4096;
String method = "POST";
String filePath = "FILE_NAME"
File uploadFile = new File(filePath);
if (!(uploadFile.isFile() && uploadFile.exists())) {
println 'File Not Found !!!!'
return;
}
URL url = new URL("http://your_url_here/" + uploadFile.name);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String contentType = "application/octet-stream"
httpConn.setDoOutput(true);
httpConn.setRequestMethod(method);
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Content-type", contentType);
OutputStream outputStream = httpConn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
println "Response message : "+httpConn.getResponseMessage();
i want to copy xml file in data directory..i did this but the below code can't copy xml file in data directory.
private void copyAsset(){
AssetManager assetmanager=getAssets();
InputStream in=null;
OutputStream out=null;
String filename="deathtrack.xml";
try {
in=assetmanager.open(filename);
out=new FileOutputStream(Environment.getDataDirectory().toString()+"/" +filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (IOException e)
{
Log. e ( "tag" , "Failed to copy asset file: " , e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8" ));
int n;
while ((n= reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
if anyone knows this how to do ?please help me.
I don't understand why you use
Writer writer = new StringWriter();
copyFile function is simple:
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
My current Android application downloads a number of audio files. When I employ this code to execute the download I get file not found exception:
try {
final URL downloadFileUrl = new URL("http://filelocation/url.m4a");
final HttpURLConnection httpURLConnection = (HttpURLConnection) downloadFileUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
mTrackDownloadFile = new File(Record.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = httpURLConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (final Exception exception) {
Log.i(TAG, "doInBackground - exception" + exception.getMessage());
exception.printStackTrace();
mTrackDownloadFile = null;
}
When i employ this code it works fine:
try {
final URL downloadFileUrl = new URL("http://filelocation/url.m4a");
final URLConnection urlConnection = downloadFileUrl.openConnection();
mTrackDownloadFile = new File(PlayOpponent.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = urlConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (final Exception exception) {
Log.i(TAG, "doInBackground - exception" + exception.getMessage());
exception.printStackTrace();
mTrackDownloadFile = null;
}
Can someone please point out where I am going wrong?
According to this blog removing
httpURLConnection.setDoOutput(true);
in your code may solve the problem. It's said to be a ICS issue.
I am loading a image from the web to the local android phone. The code that I have for writing to a file is as follows
BufferedInputStream bisMBImage=null;
InputStream isImage = null;
URL urlImage = null;
URLConnection urlImageCon = null;
try
{
urlImage = new URL(imageURL); //you can write here any link
urlImageCon = urlImage.openConnection();
isImage = urlImageCon.getInputStream();
bisMBImage = new BufferedInputStream(isImage);
int dotPos = imageURL.lastIndexOf(".");
if (dotPos > 0 )
{
imageExt = imageURL.substring(dotPos,imageURL.length());
}
imageFileName = PATH + "t1" + imageExt;
File file = new File(imageFileName);
if (file.exists())
{
file.delete();
Log.d("FD",imageFileName + " deleted");
}
ByteArrayBuffer baf = new ByteArrayBuffer(255);
Log.d("IMAGEWRITE", "Start to write image to Disk");
int current = 0;
try
{
while ((current = bisMBImage.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("IMAGEWRITE", "Image write to Disk done");
}
catch (IOException e)
{
e.printStackTrace();
}
isImage.close();
}
catch (IOException e)
{
Log.d("DownloadImage", "Error: " + e);
}
finally
{
isImage = null;
urlImageCon = null;
urlImage = null;
}
For some reason the whole writing to a file takes 1 minute. Is there a way I can optimize this ?
Your buffer is very small: 255 bytes. You could make it 1024 times bigger (255 kilobytes). This is an acceptable size and this would certainly speed up the thing.
Also, this is very slow as it reads the bytes one by one:
while ((current = bisMBImage.read()) != -1) {
baf.append((byte) current);
}
You should try using the array version of read() instead: read(byte[] buffer, int offset, int byteCount) with an array as large as what I have described above.
You should use the Android HttpClient for file fetching over the java URL Connection. Also your Buffer is very small.
Try this snipped:
FileOutputStream f = new FileOutputStream(new File(root,"yourfile.dat"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = is.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!