How to download/export .txt file in java? - java

I formed an url in the controller.When I hit that url i need to export a .txt file.As I am new to this concept , I have a doubts ,
1) Do we need to import any jar file to export .txt file as like we add jars for pdf and xls ?
I have tried like below..But i dont get any result by it.I didn't add any jar file ..
FileWriter writer = new FileWriter("MyFile.txt", true);
writer.write("Hello World");
writer.write("\r\n"); // write new line
writer.write("Good Bye!");
writer.close();

In a couple of projects I've used this utility class from codejava.net
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A utility that downloads a file from a URL.
* #author www.codejava.net
*
*/
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}

The code i have written is just a three lines to download the .txt file.
Thank you all For the help.
I am just posting my answer because just to download a empty file who need for the beginners.
Adding HttpServletResponse servletResponse dependency,
OutputStream out = servletResponse.getOutputStream();
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"Report"+".txt\";");
servletResponse.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = servletResponse.getOutputStream();
outStream.close();

Related

In Groovy, how to properly get the file from HttpServletRequest

I am writing a REST API in Groovy script that will receive a file upload from client side.
The REST API will receive the file via HttpServletRequest.
I am trying to get the file from HttpServletRequest by getting its InputStream, then convert it to File to save to proper folder.
My code is as below:
RestApiResponse doHandle(HttpServletRequest request, RestApiResponseBuilder apiResponseBuilder, RestAPIContext context) {
InputStream inputStream = request.getInputStream()
def file = new File(tempFolder + "//" + fileName)
FileOutputStream outputStream = null
try
{
outputStream = new FileOutputStream(file, false)
int read;
byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
finally {
if (outputStream != null) {
outputStream.close();
}
}
inputStream.close();
// the rest of the code
}
The files are created, but all of them are corrupted.
When I try to open them with Notepad, all of them have, at the beginning, some thing similar to the below:
-----------------------------134303111730200325402357640857
Content-Disposition: form-data; name="pbUpload1"; filename="Book1.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Am I doing this wrong? How do I get the file correctly?
Found the solution with MultipartStream
import org.apache.commons.fileupload.MultipartStream
import org.apache.commons.io.FileUtils
InputStream inputStream = request.getInputStream()
//file << inputStream;
String fileName = "";
final String CD = "Content-Disposition: "
MultipartStream multipartStream = new MultipartStream(inputStream, boundary);
//Block below line because it always return false for some reason
// but should be used as stated in document
//boolean nextPart = multipartStream.skipPreamble();
//Block below line as in my case, the part I need is at the first part
// or maybe I should use it and break after successfully get the file name
//while(nextPart) {
String[] headers = multipartStream.readHeaders().split("\\r\\n")
ContentDisposition cd = null
for (String h in headers) {
if (h.startsWith(CD)) {
cd = new ContentDisposition(h.substring(CD.length()));
fileName = cd.getParameter("filename"); }
}
def file = new File(tempFolder + "//" + fileName)
ByteArrayOutputStream output = new ByteArrayOutputStream(1024)
try
{
multipartStream.readBodyData(output)
FileUtils.writeByteArrayToFile(file, output.toByteArray());
}
finally {
if (output != null) {
output.flush();
output.close();
}
}
inputStream.close();

How do I download a file that is embedded in a web site?

At this moment I can only download files that has this type of format:
https://jdbc.postgresql.org/download/postgresql-8.1-415.jdbc2.jar
But how do I download files that aren't visible in the url file?
For e.g Skype's url path:
http://www.skype.com/sv/download-skype/skype-for-mac/downloading/
As you guys can see, there is no way I can download the file using
filePath.subString(filePath.lastIndexOf("/") + 1);
So are there other ways to do this? I did find the file embedded in the page using FireBug which is
http://www.skype.com/go/getskype-macosx.dmg
My question is, can I programmatically go through the page and get access to this file?
Here is the code which works fine for downloading
public static void fileDownload(String urlFile) throws IOException {
URL url = new URL(urlFile);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
String contentType = httpURLConnection.getContentType();
int contentLength = httpURLConnection.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = urlFile.substring(urlFile.lastIndexOf("/") + 1, urlFile.length());
}
System.out.println("Content-type= " + contentType);
System.out.println("Disposition= " + disposition);
System.out.println("Content-length= " + contentLength);
System.out.println("File name= " + fileName);
InputStream inputStream = httpURLConnection.getInputStream();
String saveFilePath = getDesiredPath() + File.separator + fileName;
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath);
int byteRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((byteRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileOutputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied httpCode=" + responseCode);
}
httpURLConnection.disconnect();
}
It's my first time working with file management and this code is actually taken from here.
You can download the file if the file download link is embedded in the page.
Something like this in the web page html:
. . .
Download Skype
. . .
For downloading the page and scanning it for links you may use JSoup
Code may look something like this:
Document doc = Jsoup.connect("http://example.com/").get();
Elements anchors = doc.select("a");
// Untested code
for (var anchor of anchors) // ECMA 6 (i think)
{
if (anchor.href.endsWith(".exe")
{
// if href is not full url i.e. not starting with http://
var downloadLink = url + anchor.href;
// Download the file with the about url
}
}

Video Using HTML 5 and servlet

Below given code is for video streaming. This is fine with IE9 and firefox but it is not fine with Chrome and Mac Safari.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class VideoStreamServlet
*/
public class VideoStreamServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public VideoStreamServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String range = request.getHeader("range");
String browser = request.getHeader("User-Agent");
System.out.println(browser);
if(browser.indexOf("Firefox") != -1){
System.out.println("==========ITS FIREFOX=============");
byte[] data = getBytesFromFile(new File("D:/media/final.ogg"));
response.setContentType("video/ogg");
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if(browser.indexOf("Chrome") != -1){
System.out.println("==========ITS Chrome=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mp4");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if(browser.indexOf("MSIE") != -1) {
System.out.println("==========ITS IE9=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mpeg");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "text/x-dvi");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if( browser.indexOf("CoreMedia") != -1) {
System.out.println("============ Safari=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mpeg");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
//response.setContentLength(data.length);
//response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
// response.setHeader("Accept-Ranges", " text/*, text/html, text/html;level=1, */* ");
// response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
//System.out.println("\nDEBUG: FileInputStream is " + file);
// Get the size of the file
long length = file.length();
//System.out.println("DEBUG: Length of " + file + " is " + length + "\n");
/*
* You cannot create an array using a long type. It needs to be an int
* type. Before converting to an int type, check to ensure that file is
* not loarger than Integer.MAX_VALUE;
*/
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large to process");
return null;
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while ( (offset < bytes.length)
&&
( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
return bytes;
}
}
Honestly, this approach is absolutely not right.
You are sniffing the user agent in the server side and depending the business job on it. This is in all cases a bad idea. If all you want is to specify a different file depending on the user agent, then rather do it in the HTML side, with help of JavaScript or CSS. Both client side languages are able to identify the real browser without the need to sniff the user agent string (which is namely spoofable).
You are not responding correctly on Range requests. You're sending the complete file back instead of the requested Range. Firefox and IE do not use range requests and that's why it "works". Chrome and Safari use range requests.
This should be possible without sniffing the user agent and properly responding to Range requests by RandomAccessFile instead of File and byte[]. It's only pretty a lot of code to take all HTTP specification requirements into account, so here's just a link where you can find a concrete example of such a servlet: FileServlet supporting resume and caching.
However, much better is to delegate the job to the servletcontainer's default servlet. If it's for example Tomcat, then all you need to do is to add the following line to /conf/server.xml:
<Context docBase="D:\media" path="/media" />
This way the desired media files are just available by http://localhost:8080/media/final.ogg and http://localhost:8080/media/final.mp4 without the need to homegrow a servlet.
This seems to be more of a format support issue.
You can try ogg format. The HTML5 code is
<audio controls="controls">
  <source src="song.ogg" type="audio/ogg" />
  Your browser does not support the audio tag.
</audio>
Google Chrome does not support H.264 (includes mp4) so you need to use final.ogg with google chrome as well. while for safari you need to change this line
browser.indexOf("CoreMedia") != -1
add "Safari" instead of "CoreMedia"
i hope it works.
String diskfilename = "final.mp4";
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
Just comment these two lines and then run on chrome your video will play.

Download a file through an HTTP Get in java

I've written a download Servlet to return a file based on a messageID parameter. Below is the doGet method.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This messageID would be used to get the correct file eventually
long messageID = Long.parseLong(request.getParameter("messageID"));
String fileName = "C:\\Users\\Soto\\Desktop\\new_audio1.amr";
File returnFile = new File(fileName);
ServletOutputStream out = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType("C:\\Users\\Soto\\Desktop\\new_audio1.amr");
response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
response.setContentLength((int)returnFile.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + "new_audio.amr" + "\"");
FileInputStream in = new FileInputStream(returnFile);
byte[] buffer = new byte[4096];
int length;
while((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
I then wrote some code to retrieve the file.
String url = "http://localhost:8080/AudioFileUpload/DownloadServlet";
String charset = "UTF-8";
// The id of the audio message requested
String messageID = "1";
//URLConnection connection = null;
try {
String query = String.format("messageID=%s", URLEncoder.encode(messageID, charset));
//URLConnection connection;
//URL u = new URL(url + "?" + query);
//connection = u.openConnection();
//InputStream in = connection.getInputStream();
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet httpGet = new HttpGet(url + "?" + query);
HttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
InputStream in = response.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Soto\\Desktop\\new_audio2.amr"));
byte[] buffer = new byte[4096];
int length;
while((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
//connection = new URL(url + "?" + query).openConnection();
//connection.setRequestProperty("Accept-Charset", charset);
//InputStream response = connection.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now this code works fine. I can download the audio file and it works correctly. What I want to know is how to, if possible, get the name of the file as it is downloaded instead of giving it my own name. Also, is it possible to get the file without having to read from the stream (maybe some library that does it for you)? I kind of want to hide the dirty stuff.
Thanks
For setting the download file name do the following on response object in Servlet code
response.setHeader("Content-disposition",
"attachment; filename=" +
"new_audio1.amr" );
EDIT:
I see you are already doing it. Just try removing the slashes you have added.
With attachment, the file will be served with the provided name properly. When inline, browsers seem to ignore filename, and usually give the servletname part of the URL as default name when saving the inline contents.
You could try mapping that URL to an appropriate filename, if that is suitable.
Here's a SO related question: Securly download file inside browser with correct filename
You may also find this link useful: Filename attribute for Inline Content-Disposition Meaningless?
I think you cannot download file without streaming. For I/O you must use stream.

file upload using java servlet as a service without a web browser

I am very new to java and servlet programming.
I am not sure whether it is possible to write a servlet which when passed a URL from the local client machine, uploads the file to the server.
basically on the client machine we have a C# program and on the server side we have Apache-tomcat installed. I need to upload file(s) to the server using C# program on client machine.
Should I provide any more information (?)
Thanks in Advance
Note this code illustrates the general idea and not guaranteed to work without modification.
The C# file upload part
// this code shows you how the browsers wrap the file upload request, you still can fine a way simpler code to do the same thing.
public void PostMultipleFiles(string url, string[] files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary +"\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "file" + i, files[i]);
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
}
httpWebRequest.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
try
{
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string var = reader.ReadToEnd();
}
catch (Exception ex)
{
response.InnerHtml = ex.Message;
}
httpWebRequest = null;
}
and to understand how the above code was written you might wanna take a look at How does HTTP file upload work?
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
and finally all you have to do is to implement a servlet that can handle the file upload request, then you do whatever that you want to do with the file, take a look at this file upload tutorial
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}

Categories

Resources