Display Images from Folder using java - java

I am a newbie in java and I want to display all the images from a system folder, viz. E://New
I am using a servlet but don't know how to proceed using it.
The servlet is:
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("E:\\new\\");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch = 0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
Thanks.

I think it can be made by this code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File(pathToWebToyourfile);
BufferedImage bi = ImageIO.read(f);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.close();
}

Related

Relative path in servlet for ServletOutputStream

I am reading servlet programming . While implementing ServletOutputStream for reading image from relative path it is throwing file not found exception .
I have tried multiple ways but failed , below is the snapshot of relevant code and folder structure in eclipse .
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
arg1.setContentType("image/jpeg");
ServletOutputStream out = arg1.getOutputStream();
FileInputStream fis = new FileInputStream("images/myimage.jpg");
BufferedInputStream bin = new BufferedInputStream(fis);
BufferedOutputStream boit = new BufferedOutputStream(out);
int ch = 0;
while((ch = bin.read() ) != -1){
boit.write(ch);
}
boit.close();
bin.close();
fis.close();
out.close();
}
}
Get the ServletContext. Then get the resource as a stream.
final InputStream imageStream = arg0.getServletContext().getResourceAsStream("/images/myiamge.jpg");

Download CSV file in Java Servlet

String fileName = "/CSVLogs/test";
String fileType = "csv";
resp.setContentType(fileType);
resp.setHeader("Content-disposition","attachment; filename=test.csv");
File my_file = new File(fileName);
OutputStream out = resp.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
I need to download a csv file but it seems to return "java.lang.IllegalStateException: WRITER"
<form enctype="multipart/form-data" action="/TestServlet/ConfigServlet?do=downloadLogs" method="post" style="height:68px;">
UPDATE
resp.setContentType("application/octet-stream");
try
{
OutputStream outputStream = resp.getOutputStream();
InputStream in = StorageUtil.getInstance().getFile("/CSVLogs/test.csv").getInputStream();
/* InputStream in = StorageUtil.getInstance().getCSVLogsZip().getInputStream();*/
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
in.close();
outputStream.flush();
}
}
catch(Exception e) {
System.out.println(e.toString());
}
I still get the same error.
java.lang.IllegalStateException: WRITER
(drunk) Why am I getting this error >_<
Try this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
in.close();
outputStream.flush();
}
}
catch(Exception e)
{
model.closeConnection();
System.out.println(e.toString());
}
}
public void downloadFile(HttpServletResponse response){
String sourceFile = "c:\\source.csv";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.csv";
response.setContentType("text/csv");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}
And the stream method should be like this.
private long stream(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
java/servlet code you supplied works perfectly fine.
i call the servlet CSVD as below:
< form enctype="multipart/form-data" action="CSVD" method="post" style="height:68px;">
<input type="submit" value="submit" />
< /form>
or through anchor this way < a href="/CSVDownloadApp/CSVD">click here to download csv< /a>
possibly your error is coming for a different reason.
Try this:
response.setContentType("application/x-rar-compressed");
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
For writing the file in OutputStream, try following
FileInputStream fis = new FileInputStream("your_csv_file.csv");
byte[] b = new byte[fis.available()];
outputStream.write(b);
outputStream.flush();
outputStream.close();

Filenotfoundexception on newer versions of android API Level 4 and later

I am working on a project with google maps where i try to retrieve bitmaps from URL and save it to internal memory.After downloading the bitmap into internal memory i try to read it from memory using the following code:
public Bitmap getImageBitmap(Context context, String name) {
FileInputStream fis = null;
try {
File myFile = new File (path_file + File.separator + name);
fis = new FileInputStream(myFile);
Bitmap b = BitmapFactory.decodeStream(fis);
return b;
} catch(Exception e) {
return null;
} finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The problem is that the code works fine on Android 2.6 , but it throws Filenotfoundexception at this line
fis = new FileInputStream(myFile);
Why does the code work fine on older versions of android but throws exception on newer versions of android?How do i fix the issue?
EDIT:
The issue was with the code which downloads the bitmap:
The code that i am using is:
public void downloadfile(String path,String filepath)
{
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
The code throws NetworkonMainThreadException at this line: InputStream is = ucon.getInputStream();
This error is thrown only on the newer android version.Please help!!
Try this..
Just use
path_file=MainActivity.this.getFilesDir();
EDIT
class downloadfile extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... urls) {
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
}
}
Instead if calling downloadfile method use below
new downloadfile().execute();
You are trying to perform a network related operation in Main thread,you are getting this NetworkonMainThreadException.
Refer to my answer here for more explanation.
In your case try downloading the bitmap file in worker thread. You can use an Asynctask for it and download bitmap in doInBackground().
Refer this example

Stream Corrupted Exception When calling Jasper Report

I have used a fileDownloadActionListener for opening a jasper report from an ADF form. First time, it's opening correctly. But the second time onwards it gives an error message on the application saying, "The file was not downloaded or was not downloaded correctly."
This is my code:
public void reportAction(FacesContext ctx,OutputStream output) throws FileNotFoundException,NamingException,
SQLException, IOException, JRException,
ClassNotFoundException,
InstantiationException,
IllegalAccessException,StreamCorruptedException {
File input = null;
Connection conn = null;
String branchId = getBranchId().getValue().toString();
Map reportParameters = new HashMap();
reportParameters.put("branchId", branchId);
bindings = this.getBindings();
ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
ServletOutputStream servletOutputStream;
servletOutputStream = response.getOutputStream();
String reportPath = ctx.getExternalContext().getInitParameter("reportpath");
input = new File(reportPath+"testJob.jasper");
byte[] bytes= null;
if(bindings!=null){
OperationBinding ob = bindings.getOperationBinding("getCurrentConnection");
ob.execute();
conn = (Connection)ob.getResult();
System.out.println("Report Path===========>"+input.getPath().toString());
if(input.getPath()!=null&&reportParameters!=null&&conn!=null){
JRPdfExporter pdfExporter = new JRPdfExporter();
bytes = JasperRunManager.runReportToPdf(input.getPath(), reportParameters, conn);
JasperPrint print = JasperFillManager.fillReport(input.getPath(),reportParameters,conn);
pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, input.getPath());
pdfExporter.exportReport();
response.addHeader("Content-disposition", "attachment;filename=testJob1.pdf");
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
File file = new File(input.getPath());
output = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bui = new BufferedInputStream(fis);
int readBytes = 0;
while ((readBytes = bui.read()) != -1)
output.write(readBytes);
bui.close();
fis.close();
servletOutputStream.flush();
servletOutputStream.close();
ctx.responseComplete();
}
}
else{
ctx.addMessage(null,new FacesMessage("No bindings configured for this page"));
}
}

Write mp3 file to disk while playing in Java

I have an application playing remote MP3 files over HTTP using the JLayer/BasicPlayer libraries. I want to save the played mp3 files to disk without re-downloading them.
This is the code using the JLayer based BasicPlayer for Playing the MP3 file.
String mp3Url = "http://ia600402.us.archive.org/6/items/Stockfinster.-DeadLinesutemos025/01_Push_Push.mp3";
URL url = new URL(mp3Url);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BasicPlayer player = new BasicPlayer();
player.open(bis);
player.play();
How would I save the mp3 file to disk?
To avoid having to go through the bytes twice, you need to wrap the input stream from the connection in a filter that writes any data that is read to an output stream, i.e. a kind of a "tee pipe input stream." Such a class is not that difficult to write yourself, but you can save the work by using TeeInputStream from the Apache Commons IO library.
Apache Commons IO: http://commons.apache.org/io/
TeeInputStream javadoc: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/TeeInputStream.html
Edit: Proof-of-concept:
import java.io.*;
public class TeeInputStream extends InputStream {
private InputStream in;
private OutputStream out;
public TeeInputStream(InputStream in, OutputStream branch) {
this.in=in;
this.out=branch;
}
public int read() throws IOException {
int read = in.read();
if (read != -1) out.write(read);
return read;
}
public void close() throws IOException {
in.close();
out.close();
}
}
How to use it:
...
BufferedInputStream bis = new BufferedInputStream(is);
TeeInputStream tis = new TeeInputStream(bis,new FileOutputStream("test.mp3"));
BasicPlayer player = new BasicPlayer();
player.open(tis);
player.play();
BufferedInputStream in = new BufferedInputStream(is);
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePathAndFilename)));
byte[] buf = new byte[256];
int n = 0;
while ((n=in.read(buf))>=0) {
out.write(buf, 0, n);
}
out.flush();
out.close();
You can first write the stream to disk with FileInputStream. Then reload the stream from file.
Wrap you own InputStream
class myInputStream extends InputStream {
private InputStream is;
private FileOutputStream resFile;
public myInputStream(InputStream is) throws FileNotFoundException {
this.is = is;
resFile = new FileOutputStream("path_to_result_file");
}
#Override
public int read() throws IOException {
int b = is.read();
if (b != -1)
resFile.write(b);
return b;
}
#Override
public void close() {
try {
resFile.close();
} catch (IOException ex) {
}
try {
is.close();
} catch (IOException ex) {
}
}
}
and use
InputStream is = conn.getInputStream();
myInputStream myIs = new myInputStream(is);
BufferedInputStream bis = new BufferedInputStream(myIs);

Categories

Resources