Error while downloading a file from url - java

I am trying to read a file from url and making it a File Type.
Below is the code
public File fileFromUrl(String str) throws IOException
{
File file = new File ("image.png");
URL url = new URL (str);
InputStream input = url.openConnection().getInputStream();
try {
OutputStream output = new FileOutputStream (file);
try {
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
return file;
}
However I am experiencing error at OutputStream output = new FileOutputStream (file);
Kindly tell me how can I make File of my url

Fine. Instead of File file = new File ("image.png"); use absolute path for the file. Like File file = new File ("<absolute-path-from-root-directory>");

It would be helpful if you have posted the exception that you are getting, but my guess is that you don't have write permissions to the current working directory in which you are trying to create your output file.
If you want to see where it tries to write the file, add this diagnostic to your program:
System.out.println(
"Absolute path of image.png: <" + file.getAbsolutePath( ) + ">"
);

Related

Using LZ4 to Add to an existing .lz4 (zip) in Java

I am compressing in java using the following and the LZ4 library. If I try to call this method again on the same file name, it overwrites with the new contents instead of appending. Is there a way to append using LZ4? I just want to add another file to the existing zip archive at a later time.
public void zipFile(File[] fileToZip, String outputFileName, boolean activeZip)
{
try (FileOutputStream fos = new FileOutputStream(new File(outputFileName));
LZ4FrameOutputStream lz4fos = new LZ4FrameOutputStream(fos);)
{
for (File a : fileToZip)
{
try (FileInputStream fis = new FileInputStream(a))
{
byte[] buf = new byte[bufferSizeZip];
int length;
while ((length = fis.read(buf)) > 0)
{
lz4fos.write(buf, 0, length);
}
}
}
}
catch (Exception e)
{
LOG.error("Zipping file failed ", e);
}
}
The only way I could figure out how to do this is to send
new FileOutputStream(new File(outputFileName),false)
in the try-with-resources

How to read a binary file, modify the same file and save the file with the modifications?

I am currently working a project and we have divided it in modules, in one of them, we have a file ( .exe ) extension. I decided to open it in binary format and read the contents of it, modify them. But, I am not to modify the changes and save it in the same file. When I am trying to do so, it says 0KB. It's working perfectly fine when using two files.
Here is the source code :
public static void main(String[] args) {
String strSourceFile="E:/e.exe";
String strDestinationFile="E:/f.exe";
try
{
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while( (noOfBytes = fin.read(b)) != -1 )
{
fout.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin.close();
fout.close();
Use RandomAccessFile or You can also create a new file with your changes save it and delete the original one. Once original file is deleted then rename this new file to the original one.
You are trying to read and write the same file with the input and the output stream so the file is not getting copied while you try to do it with the same file. Instead, use a middle file as the buffer, as in the below code I have used the f.exe as the middle buffer, next I have copied the data from the buffer file again to the original file jar.exe, at last you need to delete the buffer file.
Here is the below code :
String strSourceFile = "C:/jar.exe";
String strDestinationFile = "C:/f.exe";
FileInputStream fin = new FileInputStream(strSourceFile);
FileOutputStream fout = new FileOutputStream(strDestinationFile);
byte[] b = new byte[1];
int noOfBytes = 0;
System.out.println("Copying file using streams");
while ((noOfBytes = fin.read(b)) != -1) {
fout.write(b, 0, noOfBytes);
}
fin.close();
fout.close();
String strDestinationFile1 = "C:/jar.exe";
FileInputStream fin1 = new FileInputStream(strDestinationFile);
FileOutputStream fout1 = new FileOutputStream(strDestinationFile1);
while ((noOfBytes = fin1.read(b)) != -1) {
fout1.write(b, 0, noOfBytes);
}
System.out.println("File copied!");
//close the streams
fin1.close();
fout1.close();
File file = new File("C:/f.exe");
file.delete();

Reading gzip files inside gzip file using Java

Using Java I have to read text files which are inside gz file which is in another .tar.gz
gz_ltm_logs.tar.gz is the filename. It then has files ltm.1.gz, ltm.2.gz inside it and then these files have text files in them.
I wanted to do it using java.util.zip.* only but if it is impossible then I can look at other libraries.
I thought I will be able to do it using java.util.zip. But doesn't seem straightforward
Here's some code to give you an idea. This method will try to extract a given tar.gz file to outputFolder.
public static void extract(File input, File outputFolder) throws IOException {
byte[] buffer = new byte[1024];
GZIPInputStream gzipFile = new GZIPInputStream(new FileInputStream(input));
ByteOutputStream tarStream = new ByteOutputStream();
int gzipLengthRead;
while ((gzipLengthRead = gzipFile.read(buffer)) > 0){
tarStream.write(buffer, 0, gzipLengthRead);
}
gzipFile.close();
org.apache.tools.tar.TarInputStream tarFile = null;
// files inside the tar
OutputStream out = null;
try {
tarFile = new org.apache.tools.tar.TarInputStream(tarStream.newInputStream());
tarStream.close();
TarEntry entry = null;
while ((entry = tarFile.getNextEntry()) != null) {
String outFilename = entry.getName();
if (entry.isDirectory()) {
File directory = new File(outputFolder, outFilename);
directory.mkdirs();
} else {
File outputFile = new File(outputFolder, outFilename);
File outputDirectory = outputFile.getParentFile();
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
out = new FileOutputStream(outputFile);
// Transfer bytes from the tarFile to the output file
int innerLen;
while ((innerLen = tarFile.read(buffer)) > 0) {
out.write(buffer, 0, innerLen);
}
out.close();
}
}
} finally {
if (tarFile != null) {
tarFile.close();
}
if (out != null) {
out.close();
}
}
}

Extracting zip file into a folder throws "Invalid entry size (expected 46284 but got 46285 bytes)" for one of the entry

When I am trying to extract the zip file into a folder as per the below code, for one of the entry (A text File) getting an error as "Invalid entry size (expected 46284 but got 46285 bytes)" and my extraction is stopping abruptly. My zip file contains around 12 text files and 20 TIF files. It is encountering the problem for the text file and is not able to proceed further as it is coming into the Catch block.
I face this problem only in Production Server which is running on Unix and there is no problem with the other servers(Dev, Test, UAT).
We are getting the zip into the servers path through an external team who does the file transfer and then my code starts working to extract the zip file.
...
int BUFFER = 2048;
java.io.BufferedOutputStream dest = null;
String ZipExtractDir = "/y34/ToBeProcessed/";
java.io.File MyDirectory = new java.io.File(ZipExtractDir);
MyDirectory.mkdir();
ZipFilePath = "/y34/work_ZipResults/Test.zip";
// Creating fileinputstream for zip file
java.io.FileInputStream fis = new java.io.FileInputStream(ZipFilePath);
// Creating zipinputstream for using fileinputstream
java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(new java.io.BufferedInputStream(fis));
java.util.zip.ZipEntry entry;
while ((entry = zis.getNextEntry()) != null)
{
int count;
byte data[] = new byte[BUFFER];
java.io.File f = new java.io.File(ZipExtractDir + "/" + entry.getName());
// write the files to the directory created above
java.io.FileOutputStream fos = new java.io.FileOutputStream(ZipExtractDir + "/" + entry.getName());
dest = new java.io.BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1)
{
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
zis.closeEntry();
}
catch (Exception Ex)
{
System.Out.Println("Exception in \"ExtractZIPFiles\"---- " + Ex.getMessage());
}
I can't understand the problem you're meeting, but here is the method I use to unzip an archive:
public static void unzip(File zip, File extractTo) throws IOException {
ZipFile archive = new ZipFile(zip);
Enumeration<? extends ZipEntry> e = archive.entries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
File file = new File(extractTo, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
InputStream in = archive.getInputStream(entry);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
IOUtils.copy(in, out);
in.close();
out.close();
}
}
}
Calling:
File zip = new File("/path/to/my/file.zip");
File extractTo = new File("/path/to/my/destination/folder");
unzip(zip, extractTo);
I never met any issue with the code above, so I hope that could help you.
Off the top of my head, I could think of these reasons:
There could be problem with the encoding of the text file.
The file needs to be read/transferred in "binary" mode.
There could be an issue with the line ending \n or \r\n
The file could simply be corrupt. Try opening the file with a zip utility.

FileOutputStream crashes with "open failed: EISDIR (Is a directory)" error when downloading image

I'm trying to download an iamge from the internet, Here is the code:
try {
String imgURL = c.imgURL;
String imgPATH = c.imgPATH;
URL url = new URL(imgURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
try {
File f = new File(imgPATH);
f.mkdirs();
BufferedInputStream input = new BufferedInputStream(url.openStream());
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(imgPATH), 8192); // CRASH HERE
byte data[] = new byte[8192];
long total = 0;
int count = 0;
int updateUILimiter = 0;
while ((count = input.read(data)) != -1) {
total += count;
if (updateUILimiter == 20)
// publishProgress((int) (total * 100 / lenghtOfFile));
updateUILimiter = 0;
else
updateUILimiter++;
output.write(data, 0, count);
if (isCancelled()) {
output.flush();
output.close();
input.close();
return null;
}
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
c.imgPATH = "";
return null;
}
} catch (Exception e) {
c.imgPATH = "";
return null;
}
Here is the error message:
/mnt/sdcard/tmp/3.png: open failed: EISDIR (Is a directory)
Why is this?
" /mnt/sdcard/tmp/" exists.
3.png is a directory, because you make it so by calling f.mkdirs();. Try f.getParentFile().mkdirs() instead. From the documentation:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
(emphasis mine). In other words, the entire path contained in the File instance f is taken to be a directory name, up to and including the final part (3.png in the example output).
The problem is that you are using the function
f.mkdirs();
this function will create a folder called "3.png" instead of a file called "3.png", so delete this folder first,
then replace the function
f.mkdirs();
to
f.createNewFile();
Hope this help.
replace f.mkdirs() with f.createNewFile().
You can first make the directory and then further write the code.
URL downloadURL=null;
HttpURLConnection urlConnection=null;
InputStream inputStream=null;
FileOutputStream fos=null;
Uri uri=Uri.parse(url);
try {
downloadURL=new URL(url);
urlConnection= (HttpURLConnection) downloadURL.openConnection();
inputStream=urlConnection.getInputStream();
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/");
if(!file.exists())
{
file.mkdirs();
}
File file1=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/"+uri.getLastPathSegment());
fos=new FileOutputStream(file1);
byte[] buffer=new byte[1024];
int read=-1;
while((read=inputStream.read(buffer))!=-1)
{
/* Message.L(""+read);*/
fos.write(buffer,0,read);
}
}
Like this you can do
File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/");
if(!file.exists())
{
file.mkdirs();
}
File file1=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/myAppImages/"+uri.getLastPathSegment());
fos=new FileOutputStream(file1);
I encounter with this problem when <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
was not written correctly, so check manifest again.

Categories

Resources