Throw a file to the user - java

I'm using data handling
FileOutputStream fileOutputStream = new FileOutputStream(file_name);
workBook.write(fileOutputStream);
fileOutputStream.close();
After the code runs the file is saved somewhere in the system without any indication. I want that the file should be available to user as a pop up when we download anything of the internet and the user can save the file wherever they want.

You have to get outputstream from response and write whole file in that stream. refer to example for more detail

Related

How to create a txt file with a String content and download that txt file

I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.
Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.
I used below piece of code,
FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
Also I tried with FileWriter in place of FileOutputStream like,
FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.
You should add Content-Disposition: attachment to say browser, that it should download the file, not to open it.
See more details here
Also Struts has DownloadAction, you may use it as well.
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.
use it like this
response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");
of course this depends on which technology stack you're using.
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}

How to delete the contents of a file using the FileOutputStream class in Java?

I'm working with the FileOutputStream class in java, but I don't know how to delete "the contents" of a file (the main reason i need overwrite the file).
If you want to delete the contents of the file, but not the file itself, you could do:
PrintWriter pw = new PrintWriter("file.txt");
pw.close();
A few seconds of Googling got me this:
how to delete the content of text file without deleting itself
How to clear a text file without deleting it?
To delete the file completely, do:
File file = new File("file.txt");
f.delete();
Call File.delete() which deletes the file or directory denoted by this abstract pathname.
File f = new File("foo.txt");
if (f.delete()) {
System.out.println("file deleted");
}
The main reason i need overwrite the file ...
One way to do this is to delete the file using File.delete() or Files.delete(Path). The latter is preferable, since it can tell you why the deletion fails.
The other way is to simply open the file for writing. Provided that you don't open in "append" mode, opening a file to write will truncate the file to zero bytes.
Note that there is a subtle difference in the behavior of these two approaches. If you delete a file and then create a new one, any other application that has the same file open won't notice. By contrast, if you truncate the file, then other applications with the file open will observe the effects of the truncation when they read.
Actually, this is platform dependent. On some platforms, a Java application that tries to open a file for reading that another file has open for writing will get an exception.
Yes, you can do it with FileOutputStream. All the answers given say about PrintWriter but the same can be done with FileOutputStream. The int representation of space is 32. So simply pass the file to the instance of FileOutputStream as:
FileOutputStream out = new FileOutputStream(file);
out.write(32);
This will clear the contents of the file. Surely use this only of u want to do it with FileOutputStream only otherwise use PrintWriter.

How to download monthly Treasury Files

Up till early this year the US Treasury web site posted monthly US Receipts and Outlays data in txt format. It was easy to write a program to read and store the info. All I use were:
URL url = new URL("https://www.fiscal.treasury.gov/fsreports/rpt/mthTreasStmt/mts1214.txt")
URLConnection connection.openConnection();
InputStream is = connection.getInputStream();
Then I just read the InputStream into a local file.
Now when I try same code, for May, I get an InputStream with nothing in it.
Just clicking on "https://www.fiscal.treasury.gov/fsreports/rpt/mthTreasStmt/mts0415.xlsx" opens an excel worksheet (the download path has since changed).
Which is great if you don't mind clicking on each link separately ... saving the file somewhere ... opening it manually to enable editing ... then saving it again as a real .xlsx file (because they really hand you an .xls file.)
But when I create a URL from that link, and use it to get an InputStream, the is empty. I also tried url.openStream() directly. No different.
Can anyone see a way I can resume using a program to read the new format?
In case its of interest I now use this code to write the stream to the file bit by bit... but there are no bits, so I don't know if it works.
static void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
System.out.println("reading: " + in.read(buf));
//This is what tells me it is empty, i.e. the loop below is ignored.
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Any help is appreciated.

Logging results to an excel file (apache poi), error if I open the file while program is still running

I have a program that does various tasks and then logs the results to an excel file. I'm using Apache POI.
The program is working perfectly and is logging everything as I want it. However, it can take hours to complete, and I noticed that if I open the excel file while it's still running, it fails and throws a java.io.FileNotFoundException exception with this message (The process cannot access the file because it is being used by another process) when it tries to save to the file.
My guess is that by opening the excel file, the program is getting locked out of writing to it. How can I get around this? Is there a way to lock users out of opening the file while the program runs (Forcing them to access it as read-only)?
This is the code that gets used to initially create the file:
HSSFWorkbook wb = new HSSFWorkbook();
//.. bunch of POI stuff here
FileOutputStream fileOut = new FileOutputStream("C:\\ file path here");
wb.write(fileOut);
wb.close();
fileOut.close();
And then in a separate logResults() method, the file is accessed and saved:
FileInputStream file = new FileInputStream(new File("C:\\ file path here"));
HSSFWorkbook wb = new HSSFWorkbook(file);
//.. bunch more POI stuff here
FileOutputStream fileOut = new FileOutputStream("C:\\ file path here");
wb.write(fileOut);
wb.close();
fileOut.close();
I don't think you can do anything in Java side.
You may need do something in Excel file as follows
Private Sub Workbook_Open()
If ThisWorkbook.ReadOnly
Then
MsgBox "File already in use"
ThisWorkbook.Close
savechanges:=False
End If
End Sub
'This is workbook event code.
'To input this code, right click on the Excel icon on the worksheet
'(or next to the File menu if you maximise your workbooks),
'select View Code from the menu, and paste the code
I found a work around. I'm not sure if it's the most elegant solution, but it seems to work well enough.
When the file is created, I set it to read only with. Then every time I will log a result, I switch it back to writeable, and then back to read only after it's saved.
Basically something like this:
File file = new File(filePath);
//..
file.setWritable(true);
FileOutputStream fileOut = new FileOutputStream(filePath);
file.setReadOnly();

Editing existing file in Android

I am trying to edit existing file on the device by-First- select the file using selector that retrieve the path of the file like this "mnt/sdcard/file.png". Then I pass it to reader to read the existing file then modify it by by shifting the Ascii of every char. Then Overwrite it again to replace the old one.
I have tested the code on a desktop app on PC files and it Works perfect, but does not work as an Android app. It worked on my device once but did not work again
About what I did:
1)Add writing on External source Permission in the Mainafest file
2)Select the file right and retrieve it path
3)Read the file content true
File file = f;
FileInputStream fin;
fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
4)Modify the file bytes
5)Write back (Overwrite) in the original file
FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
fos.write(enc_msg);
fos.write((byte)seed);
fin.close();
fos.close();
6)Set the file to null again
7)Call finish() in the onClickListner
Thanks in Advance
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
However, the device must be disconnected from USB. Otherwise you need to unplug and replug the device to see the changes.
After a lot of work, I have reached the final solution by:
1)Using Common-io library
http://commons.apache.org/proper/commons-io/download_io.cgi
2)Writing this simple line only after import common-io
FileUtils.writeByteArrayToFile(new File(file.getAbsolutePath()), myByteArray, false);
the last attribute (Fasle) for overriding the file .. Append flag

Categories