Here in my list i am having multiple files but while downloading only the first file in my list is getting downloaded.
for(FileAttachemntActionVo fileAttachemntActionVoItr : fileAttachemntActionVoList){
ServletOutputStream out = servletResponse.getOutputStream();
servletResponse.setContentType("multipart/x-mixed-replace;boundary=END");
servletResponse.setHeader("Content-Disposition","attachment; filename="+fileAttachemntActionVoItr.getAttachmentFileName());
//}
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(fileAttachemntActionVoItr.getAttachmentUrl() + fileAttachemntActionVoItr.getAttachmentFileName());
}catch(FileNotFoundException fnfe){
fnfe.getStackTrace();
}
BufferedInputStream fif = new BufferedInputStream(fileInputStream);
int i = 0;
while ((i = fif.read()) != -1) {
out.write(i);
}
fif.close();
out.close();
}
Do not close the output stream, take a look at this post. Let the container handle the stream.
Related
I've saved an array list in the android mobile storage with a .txt extension. The problem is that there are unknown characters (as it's shown in the screenshot) coming before each file name that my string does not contain these characters.
if (uri != null)
file = resolver.openFileDescriptor(uri, "w");
if (file != null) {
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
file.getFileDescriptor());
ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
for (int i = 0; i < myList.size(); i++) {
out.writeObject(removeAccents(myList.get(i).getName() +"\n"));
}
// out.flush();
out.close();
fileOutputStream.close();
file.close();
and the screenshot is:
Instead of using ObjectOutputStream, I should use OutputStreamWriter.
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
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();
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( ) + ">"
);
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.