unable to download file from java - 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();
}

Related

Apache POI - XSSFWorkbook + servlet response

I find a problem on using apache-poi. Here is my code.
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(request.getSession().getServletContext().getRealPath("/Testing.xlsx")));
XSSFSheet spreadsheet = workbook.getSheet("TempSheet");
File template = new File(request.getSession().getServletContext().getRealPath("/Testing.xlsx"));
FileOutputStream out = new FileOutputStream(template);
workbook.write(out);
out.close();
String currentTime = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String fileName = "TestingABC.xlsx";
String absoluteDiskPath = request.getSession().getServletContext().getRealPath("/Testing.xlsx");
File f = new File(absoluteDiskPath);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
try {
byte[] outputByte = new byte[4096];
while (in.read(outputByte, 0, 4096) != -1) {
outs.write(outputByte, 0, 4096);
}
outs.flush();
outs.close();
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(outs != null)
outs.close();
if(in != null)
in.close();
}catch (Exception ioe2) {
ioe2.printStackTrace();
}
}
}
Excel file is download normally, but when i open the file, the following error message display :
"When i try this, i receive the message: "We found a problem with some content in 'TestingABC.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click 'Yes'"
After i click 'Yes'
the error is as follow:
"Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded."
Actually, the file data is correct, but how can i remove this message ?
Thanks.
It work after adding content Length:
response.setContentLength((int) file.length());

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();
}

java download image directly to specified area

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.

Where is my resource file

I've a problem with android and Storage Options (Internal Storage).
I added a SSL certificate in the "raw" directory and i want to write in, into the storage.
In the moment I'm trying it with this code snippet:
InputStream is = SA.getResources().openRawResource(R.raw.myResource);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1)
{
buffer.write(data, 0, nRead);
}
buffer.flush();
FileOutputStream fos = SA.openFileOutput("Resource.crt", 0);
fos.write(buffer.toByteArray());
fos.close();
is.close();
buffer.close();
File f = new File(this.fileList()[0]);
if(f.exists())
{
Log.v("File:", "Found");
}
else
{
Log.v("File:", "Not found");
}
My File isn't found. I don't know why.
I believe fileList is just returning the filename, but you also need the directory try :
File f = new File(context.getFilesDir(), filename);
if(f.exists()){
...
Read here :
http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage

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