java download image directly to specified area - java

I already tried to download the image like this:
File file4 = new File("C:\\Users\\" + user + "\\AppData\\Roaming"
+ "\\.MINECRAFT2D\\Recources\\"
+ "tileset_texture_new_now.png");
try {
Image image = null;
URL url = new URL("http://www.mediafire.com/view/"
+ "htgmcgtg7yo5swy/tileset_texture_new_now.png");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(file4);
fos.write(response);
fos.close();
} catch (Exception e) {}
but it leaves an un-viewable image in the location. The image will say: "Photo Gallery can't open this photo or video. The file may be unsupported, damaged or corrupted." Is there a way to fix it?

try like this:
byte[] response = out.toByteArray();
Close the stream once you made the byte array
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
byte[] response = out.toByteArray();
out.close();
in.close();

Your url is pointing to 'http://www.mediafire.com/view/htgmcgtg7yo5swy/tileset_texture_new_now.png'. It does not resolve to an image/png. I believe that this is the reason of the corrupted image.
Take a look at FileUtils.copyURLToFile(URL, File), from Apache IO Commons. It might help you downloading files.

Related

zip,move and size of file which is in a server path using java

I have a file in the server, I want to create three java APIs, which will do the below three operations in dependently.
Get the file size
Move a file with different file name to a different server location
Zip the file
In my existing code we are executing Linux commands to perform those operations, unfortunately, Linux commands are not getting executed, this is due to some server/set up issue, so I am forced to use Java commands.(We use JDK 1.6)
I am not a Java developer. I have gone through some of the previously answered questions, but they are not explaining about file in server path. Any help is much appreciated.
To get the file size in bytes:
File file = new File("filename.txt");
long fileSize = file.length();
To move a file you must first copy it and then delete the original:
InputStream inStream = null;
OutputStream outStream = null;
try {
File fromFile = new File("startfolder\\filename.txt");
File toFile = new File("endfolder\\filename.txt");
inStream = new FileInputStream(fromFile);
outStream = new FileOutputStream(toFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
fromFile.delete();
} catch(IOException e) {
e.printStackTrace();
}
To zip a file:
byte[] buffer = new byte[1024];
try {
FileInputStream fileToZip = new FileInputStream("filename.txt");
FileOutputStream fileOutputStream = new FileOutputStream("filename.zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
ZipEntry zipEntry= new ZipEntry("filename.txt");
zipOutputStream.putNextEntry(zipEntry);
int len;
while ((len = fileToZip.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
fileToZip.close();
zipOutputStream.closeEntry();
zipOutputStream.close();
} catch(IOException e) {
e.printStackTrace();
}

unable to download file from java

I had written a program to get stocks data from yahoo finance website, my code used to work previously, lately it has stopped working.
When i access the same url from browser a file is downloaded,
however from java code i get and empty stream
here is sample link
These are the codes that i have tried
try{
ReadableByteChannel rbc = Channels
.newChannel(website.openStream());
FileOutputStream fos;
fos = new FileOutputStream(Type+"//"+
FileName + ".csv");
fos.getChannel().transferFrom(rbc, 0,
Long.MAX_VALUE);
fos.flush();
fos.close();
String fileName = "file.txt"; //The file that will be saved on your computer
URL link = new URL(website.toString());
//Code to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
//End download code
Runnable r1 = new Analyzer(Type+"//"+
FileName + ".csv",Type,Name);
Thread r2= new Thread(r1);
r2.start();
r2.join();
}
catch(Exception e)
{
e.getMessage();
}

Upload large files to the Google Drive

In my app, I'm uploading files to the google drive using GD API. It works fine for small file sizes, but when file size is large (ex: 200MB), it throws java.lang.OutOfMemoryError: exception. I know why it crashes it loads the whole data into the memory, can anyone suggest how can I fix this problem?
This is my code:
OutputStream outputStream = result.getDriveContents().getOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(file.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
byte[] photoBytes = baos.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
outputStream = null;
fis.close();
fis = null;
} catch (FileNotFoundException e) {
}
This line would allocate 200 MB of RAM and can definitely cause OutOfMemoryError exception:
byte[] photoBytes = baos.toByteArray();
Why are you not writing directly to your outputStream:
while (-1 != (n = fis.read(buf)))
outputStream.write(buf, 0, n);

I am transferring image file from server side to client, while reading image file i got this issue

I am using following code for reading image file from socket. It reads all the bytes from server because size of file on server and android machine are same. When i open this file it does not open the file and generate error that is the file is corrupted or too large.
public Bitmap fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
System.out.println(imageInSD);
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(imageInSD);
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ( true ) {
bytesRead = is.read(aByte);
bos.write(aByte, 0, bytesRead);
if ( is.available()==0)
break;
}
bos.flush();
bos.close();
// is.reset();
// here it give error i.e --- SkImageDecoder::Factory returned null
bitmap = BitmapFactory.decodeFile(imageInSD);
} catch (IOException ex) {
// Do exception handling
Log.i("IMSERVICE", "exception ");
}
}
return bitmap;
}
Don't use available() for this, it won't work reliably!
The docs state:
[ available() ] Returns an estimate of the number of bytes that can be read [...] It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.
Do it like:
while ( (bytesRead = is.read(aByte)) > 0 ) {
bos.write(aByte, 0, bytesRead);
}

file not saved correctly

Im trying to get image using webservice and saved to sd card. The file saved but i couldnt open the file. Once i open the file it saying "could not load image". Below is my code.
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
test = response.toString();
Blob picture = org.hibernate.Hibernate.createBlob(test.replaceAll("-", "").getBytes());
String FILENAME = "voucher1.jpg";
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=picture.getBinaryStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.close();
Please help. Thanks
I changed the format..instead use web service i just use the image url to retrieve the image and it works...
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
i assume you need to call f.flush() in order to write out all data in stream to file.
f.flush();
f.close();

Categories