List file under directory using JSP
Hi,
Does anyone have a code to list all files under a certain directory in JSP? Thanks alot!
thank you so much... l already have a code working, but l can't make it download excle file as it displays them online. l want to force download. thanks
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page errorPage="listFiles_error.jsp" %>
<%
// To change the directory that is listed, change this variable
// \ character must be escaped with a second \ as below
String directoryName = "c:\\Tomcat\\webapps\\examples\\jsp";
// This variable needs to point to the URL that will be after the
// domain name for the above directory (needs to be setup in your
// application server)
String urlName = "/examples/jsp/";
// Loads the list of files in the directory
File directory = new File(directoryName);
File[] fileList = directory.listFiles();
Hashtable sortedFiles = new Hashtable(fileList.length);
// Loops through each file
for(int i=0; i<fileList.length; i++) {
File file = fileList;
// Skip subdirectories
if(file.isDirectory())
continue;
String name = file.getName();
int dotIndex = name.indexOf('.');
// Skip files with no extension
if(dotIndex < 0 || dotIndex+1 >= name.length())
continue;
String fileName = name.substring(0,dotIndex);
String fileType = name.substring(dotIndex+1).toLowerCase();
// Only process PDF, REP, and XLS file types
if(!fileType.equals("pdf") && !fileType.equals("rep") && !fileType.equals("xls"))
continue;
// Organize like filenames for processing later
Hashtable fileTypes = (Hashtable)sortedFiles.get(fileName);
if(fileTypes == null) {
fileTypes = new Hashtable(10);
sortedFiles.put(fileName,fileTypes);
fileTypes.put(fileType,file);
%>
<html>
<head>
<title>
listFiles
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body {
background-image: url(bkg2.gif);
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
.style2 {font-size: large; color: #000066; }
.style3 {font-size: medium; color: #000066; }
-->
</style></head>
<body bgcolor="#ffffff">
<table width="100%" border="0">
<tr>
<th background="chead.gif" scope="col"><div align="left"><img src="jpmorgan_logo.gif" width="200" height="40" border="0"></div></th>
</tr>
</table>
<p> </p>
<TABLE width="700" height="106" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#000033">
<tr>
<th width="370" height="33"><div align="left" class="style2">Name</div></th>
<th width="40"><div align="left" class="style2">PDF</div></th>
<th width="40"><div align="left" class="style2">Rep</div></th>
<th width="40"><div align="left" class="style2">Excel</div></th>
</tr>
<%
// Loop through each file name, outputting the data in a tabular format.
Enumeration e = sortedFiles.keys();
while(e.hasMoreElements()) {
String fileName = (String)e.nextElement();
Hashtable fileTypes = (Hashtable)sortedFiles.get(fileName);
File pdfFile = (File)fileTypes.get("pdf");
File reportFile = (File)fileTypes.get("rep");
File excelFile = (File)fileTypes.get("xls");
%>
<tr>
<td height="63" align="left" valign="bottom"><div align="left" class="style3"><%=fileName%></DIV></td>
<% if(pdfFile != null) {
// Output the PDF Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+pdfFile.getName()%>"><img src="PDF.gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="40" align="left" valign="bottom"> </td>
<% }
%>
<% if(reportFile != null) {
// Output the Report Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+reportFile.getName()%>"><img src="Rep.gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="1" align="left" valign="bottom"> </td>
<% }
%>
<% if(excelFile != null) {
// Output the Excel Entry
%> <td width="40" align="left" valign="bottom"><a href="<%=urlName+excelFile.getName()%>"><img src="xls.Gif" width="40" height="40" border="0"></a></td>
<% } else {
%> <td width="1"> </td>
<% }
%>
</tr>
<%
%>
</table>
</body>
</html>
Similar Messages
-
Moving files into directory using shell script
Can someone tell me how I move files into directory using *nix/linux shell script?
I have files which created from stored procedures using utl_file. The files name for example:
DKH_104_12345
DKE_101_42324242
DKH_102_32432
DKE_101_34553
Then I create directories automatically for example:
/oradata/apps/dmp/output/101
/oradata/apps/dmp/output/102
/oradata/apps/dmp/output/103
/oradata/apps/dmp/output/104
Using this procedure :
CREATE OR REPLACE PROCEDURE Xorganize AS
v_item VARCHAR2(5);
v_DirName VARCHAR2(50);
v_FileName VARCHAR2(50):='xorganize';
v_FileExt VARCHAR2(5):='.sh';
v_ID UTL_FILE.file_type;
CURSOR res IS
--find the directory name from table
SELECT brn_cde FROM vcr_brn_cde ORDER BY 1;
BEGIN
--used by utl.file funtion
SELECT PRD_DIR INTO v_DirName
FROM CR_SYS_PRM
WHERE CLT_CDE ='FIF';
SELECT v_FileName||v_FileExt INTO v_FileName FROM dual;
v_ID:=UTL_FILE.FOPEN(v_DirName,v_FileName, 'w');
utl_file.PUTF(v_ID,'%s\n','@@echo OFF');
utl_file.PUTF(v_ID,'%s\n','cls');
utl_file.PUTF(v_ID,'%s\n','echo Reorganizing ...');
OPEN res;
LOOP
FETCH res INTO v_item;
EXIT WHEN res%NOTFOUND;
utl_file.PUTF(v_ID,'%s\n','mkdir '||v_item);
END LOOP;
CLOSE res;
OPEN res;
LOOP
FETCH res INTO v_item;
EXIT WHEN res%NOTFOUND;
utl_file.PUTF(v_ID,'%s\n','move _'||v_item||'_.* '||v_item||'\');
END LOOP;
CLOSE res;
utl_file.PUTF(v_ID,'%s\n','FOR /F "usebackq delims=" %%1 IN (`dir /b *.`) DO @rd/q %%1');
utl_file.PUTF(v_ID,'%s\n','cls');
utl_file.PUTF(v_ID,'%s\n','echo Reorganizing ...Done');
utl_file.fclose(v_ID);
END;
Everything works fine, BUT, the script is generated in dos/windows scripting.
Now I need to run the script in *nix/linux shell, which I still can’t do it (because of my knowledge :p).
And also I don’t know if the script already generated in *nix/linux shell version, how do I chmod +x the script from stored procedure, I can’t use ‘host’ command in my tools
Thanks a lot
-firmanIf you're using 9i then UTL_FILE.FRENAME() will execute something like a Unix mv command.
If you want to do a chmod then you'll need to check out how to use a Java Stored Procedure to execute OS calls.
Cheers, APC -
How to check files in the directory using JSP?.
Hi,
How can i check the file is directory or file and readable or writable and file size and type of file(Ex. jpg, txt, doc., etc). i want to list the specific type of file in the particular directroy.. please help me..
Regards
CHinnaWith the File class, using the methods isFile(), isDirectory(), canRead(), canWrite(), length() and getName()
With File.listFiles() you can get a directory listing. If you want to limit the amount of files returned, you can pass your own FileFilter to it.
http://java.sun.com/javase/6/docs/api/java/io/File.html -
List files in directory?
Hey there. I'm brand new to this JSP stuff. I'm developing a solution whereby a customer logs into a page, the page looks into a directory for invoices associated with that customer (this will be accomplished through naming conventions) and then gives the customer a dropdown with their invoices in it. I wanted to start with the simplest part of the code and work forward with the conditions etc. So what I want to do first is just get the page to list all the files in the invoices directory. Can anyone help me with that?
Thanks!Q&D, should list the current directory contents.
I want to do first is just get the page to list all
the files in the invoices directory. Can anyone helpimport javax.swing.*;
import java.util.*;
import java.io.*;
import java.io.OutputStream.*;
import java.io.InputStream.*;
import java.util.zip.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Date;
import javax.swing.table.*;
import java.net.URL;
import java.sql.*;
import java.net.*;
public class Servlet extends HttpServlet {
public final static String IPAddress = "127.0.0.1";
public final static String IPAddressKey = "ipaddress";
public Servlet()
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession( true );
String sessionID = session.getId();
session.putValue( "sessionID", sessionID );
session.putValue( IPAddressKey, IPAddress );
ServletContext sc = null;
RequestDispatcher rd = null;
String url = "/Dir.jsp";
sc = getServletContext();
rd = sc.getRequestDispatcher( url );
System.out.println( "S url forward " + url );
rd.forward( req, res );
<html>
<%@ page session="false" language="java" import="java.io.*" %>
<body bgcolor="white">
<font size=4>
<%
try {
File f = new File( "." );
File[] fs = f.listFiles();
for( int i = 0, ii = fs.length; i < ii; i++ )
%>
<%= fs[ i ] %><br>
<%
} catch (Exception e) {
System.err.println(e);
%>
</font>
</body>
</html> -
How To traverse files under subfolder using Traverse folder option
My files are stored as Newborn.txt under each year's subfolder, How to implement this.
Eg: C:\Ravi\N90\Newborn.txt
C:\Ravi\N91\Newborn.txt
C:\Ravi\N92\Newborn.txt
C:\Ravi\N93\Newborn.txt
Pl help me to read the files using the for each loop container"Set the folder location as C:\Ravi inside for each loop
Select the traverse subfolders option and it will iterate through all subfolders in it
set file type as *.txt and it will iterate through above listed files one by one
also see
http://www.sql-programmers.com/for-each-loop-container.aspx
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Accessing files in directory using Java SP in 10g
Hi all-
I have set up a directory in 10g which points to an existing directory in the operating system and am trying to get the list of files in it from a Java stored procedure. The directory in Oracle is called "Upload_to_Oracle" and am trying to get the files in the sp by calling:
File f1=new File("Upload_To_Oracle");
File fs[] =f1.listFiles();
System.out.println("The count of files is " + fs.length);
The problem is fs is null, so fs.length causes an exception to be thrown. Initially I was getting an error:
the Permission (java.io.FilePermission Upload_To_Oracle read) has not been granted to ILFORD. The PL/SQL to grant this is dbms_java.grant_permission('ILFORD', 'SYS:java.io.FilePermission', 'Upload_To_Oracle', 'read')
which I (think) I resolved by executing that command as SYS (this is a dev box used by just me) and logging out of sqlplus and back in.
I haven't been able to find anywhere how you're supposed to reference an Oracle directory in Java, so in all honesty, I don't know if this is how you're supposed to do it.
Any help would be appreciated.
Thanks,
IlfordI figured it out for anyone who needs something similar; the problem is that the Oracle directory is specific to particular files that Oracle will use for loading (BFiles, etc.). To get at the file system directory, I just needed to reference the actual system directory itself, as well as grant it permission.
So what it comes down to is that you should reference the directory in File() as if it truly were a regular Java app on the filesystem, making sure the appropriate permissions are set for both the user running Oracle (for file/directory access) as well as for Java access. -
Reading all files on directory using "utl_file" package...
I need to read all files in directory via PL/SQL. I don't know
name files (are data dynamics create for automation system),
only I know your extensions.
Can I do this using the package "utl_file" or I need to create
program in another language (C, C++, for example)?
Any ideas...
Thanks.Hi,
you can't do that with the UTL_FILE package (it can't retrieve
file names).
A very simple solution would be, if you created on OS-level a
file which contains the filenames of directory and then read this
file using UTL_FILE. With the information on all file names you
can enter a loop which opens and reads all files again using
UTL_FILE.
A more mundane solution could be to use the features on the iFS.
Cheers
Gerald -
How to send an attachment(file) to server using JSP
Hello,
I'm developing a small web-based mail system using JSP and
JavaMail API 1.2. I need to make a compose form which allows to
attach some file. I'm using the following HTML code:
<FORM ENCTYPE="multipart/form-data">
<INPUT TYPE="file" name="somename">
</FORM>
Would you be so kind pointing me which Java code I need to use
to implement it.
Thanks in advance and sorry for my Englishsee the api for this:
http://www.orionserver.com/docs/api/com/evermind/io/FilePostParse
r.html
you can also use this stuff:
http://www.orionsupport.com/articles/fileupload.html
I have found that Nick Newman's stuff is much better, though,
since it doesn't change with the orion api (the orion api 1.5.3
has changed, so anything you did with the above methods won't
work with 1.5.3 ;().
http://www.orionsupport.com/articles/downloads/UploadServlet.zip
regards,
the elephantwalker
www.elephantwalker.com -
List contents of Directory using File Object.
Hi. I am new to Java.
Right now I want to list the contents of a specific directory. One approach is to use FILE array. But I just cannot get it right. Am i missing out something?Thanks.
My idea was to retrieve the contents of directory and then when the form loads; the contents of directory (only directorys, not files; hence i think i can use isDirectory to check) will be loaded into a listbox (DefaultListModal i supposed)
I ran it without any errors. The Listbox is loaded; but then the listbox reads
Java.lang.String;@1a7508a
What went wrong? -
Listing files of directory on application server
hi all,
I want to download a list of files from the application server.
I tried the functions:
- SUBST_GET_FILE_LIST
- EPS_GET_DIRECTORY_LISTING
- RZL_READ_DIR_LOCAL
but the result gives me the name of my file truncated.
My filename is much longer than the functions give me.
Is there any other function, or can i bypass this problem in a way.
Thanks in advance.
Merijn.Hello,
This is a common problem with this FMs. Even SAP acknowledges this:
In EPS_GET_DIRECTORY_LISTING you have this:
data: begin of file,
dirname(75) type c, " name of directory. (possibly truncated.)
name(75) type c, " name of entry. (possibly truncated.)
end of file.
The FM uses a Kernel Call 'C_DIR_READ_NEXT' to get the list of the files in the directory. The file name is returned in the field file-name.
call 'C_DIR_READ_NEXT'
id 'TYPE' field file-type
id 'NAME' field file-name
id 'LEN' field file-len
id 'OWNER' field file-owner
id 'MTIME' field file-mtime
id 'MODE' field file-mode
id 'ERRNO' field file-errno
id 'ERRMSG' field file-errmsg.
The program RSWATCH0(trxn: AL11) also uses the Kernel call but the structure file is different.
DIrectory name can be 1024 character long & file name is 260 character long
data: begin of file,
dirname(1024) type c, " name of directory. (possibly
" truncated.)
name(260) type c, " name of entry. (possibly
" truncated.)
type(10) type c, " type of entry.
len(8) type p, " length in bytes.
owner(8) type c, " owner of the entry.
mtime(6) type p, " last modification date, seconds since 1970
mode(9) type c, " like "rwx-r-x--x": protection mode.
useable(1) type c,
subrc(4) type c,
errno(3) type c,
errmsg(40) type c,
mod_date type d,
mod_time(8) type c, " hh:mm:ss
seen(1) type c,
changed(1) type c,
end of file.
So one workaorund would be to copy EPS_GET_DIRECTORY_LISTING to some custom FM & change the length of the structure file to suit your requirement
BR,
Suhas
PS: Use of Kernel Call is for internal use only & is highly not recommended by SAP. -
Browsing and uploading a directory using jsp/jsf
Hello to all,
We can browse an upload a file to the server, but how can we browse the directory and upload it?
Thanks in advance.Remember that at the end of the day, JSP results in an HTML page so you are subject to the same restrictions as a plain ol' HTML page. So the short answer is you can't.
You can create a (signed) java applet and embed that on the page to possibly do what you want.
HTH. -
How to list files from directory in list box?
Hi all,
Here is what I want to implement: I have several pattern files that'd
be sent to special motor controller. What I want is: display these
files in the list box on the interface, so that user can click on the
file he wants, then run the program, and this file will be the input
to my controller.
Thank you!lv 6.1 attached.
cheers,
~j5
2006 Ultimate LabVIEW G-eek.
Attachments:
Get_File_Names.vi 54 KB -
Uploading a file from form using Jsp to webserver
WE tried to upload a file to a webserver. We tried different ways that we got code from this forum.
but unable to access the data sent from the browser.
Plssss go thro the code and let us know what the problem is.......
<%
try
ServletContext context = getServletContext();
InputStream mySis = request.getInputStream();
out.println(mySis.available());
BufferedReader r = new BufferedReader(new InputStreamReader(mySis));
String line = null;
StringBuffer buf = new StringBuffer();
while ((line = r.readLine())!=null) {
out.println(line);
buf.append(line);
out.println("********PRINT");
out.println(buf.toString());
}catch(Exception ee){out.print("error");}
%>
We also tried the code posted in this forum
InputStream mySis = request.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
do
myCurrentByte = mySis.read();
bos.write(myCurrentByte);
Appreciate ur help.use the FileUpload package. it's part of the jakarta commons packages. works great, decent docs. I use it in several production systems.
-
Failing to list files in remote directory using FTP
Since I've been using a proxy with FTP transport for pull files from a remote server during several months. Now it started to work just sometimes
####<Apr 11, 2011 1:33:50 PM BRT> <Error> <WliSbTransports> <WN7-6J6VJN1> <AdminServer> <pool-9-thread-1> <weblogic> <> <f2be7f1e2af484b9:-47b5d228:12f456185e7:-7ff1-000000000000002c> <1302539630973> <BEA-381602> <Error encountered while polling the resource for the service endpoint ProxyService$Infolease$1_0$ProxyServices$Contract$SendBookingConfirmationPS: com.bea.wli.sb.transports.TransportException: <user:davi_diogo>Unable to list files for directory:.
com.bea.wli.sb.transports.TransportException: <user:davi_diogo>Unable to list files for directory:.
at com.bea.wli.sb.transports.ftp.connector.FTPWorkPartitioningAgent.execute(FTPWorkPartitioningAgent.java:218)
at com.bea.wli.sb.transports.poller.TransportTimerListener.run(TransportTimerListener.java:75)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:139)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:909)
at java.lang.Thread.run(Thread.java:619)
I configured the service account with my own username, and I do make sure that I have the rights over my home\user directory. (I tested with WINSCP and putty).
I haven't done any modification to make this start happening.
following my proxy configuration:
protocol: ftp
URI: ftp://myhost/
mask: *.XML
but no success.
I said "sometimes" above because it works after ~15 tentatives. Perhaps this could be a issue in my remote server OS.
Has anyone faced this issue before?
Thanks in advance,
DavinodPlease refer -
Error encountered while polling the resource for the service endpoint
Regards,
Anuj -
How to open a pdf file in a web browser using jsp
Hi,
I have a problem opening pdf file in browser using jsp.the following is my code.Can anyone help me.Thanks
response.setContentType("application/pdf");
String filename="C:\\FictPos\\mypdf.pdf";
File file = new File(filename);
FileInputStream in = new FileInputStream(file);
OutputStream out1=response.getOutputStream();
byte[] buf = new byte[4096];
int count = 0;
while ((count = in.read(buf)) >= 0)
out1.write(buf, 0, count);
in.close();
out1.close();
}Don't know the problem specifically, but here are some suggestions to investigate:
Does it show anything in the page when you view source on it?
I would recommend using a servlet rather than a JSP page for this, if only for the fact the JSPs can insert carriage returns into places where you might not want them to. This might screw up the PDF file format?
Try setting the a link to the jsp, right-click and "save target as..." just to see if it gets any response at all - ie bypass the browser display.
Good luck,
evnafets
Maybe you are looking for
-
Image processing with BLOBS: how to write BufferedImage to a BLOB
Hi everybody - thanks in advance for any input on that topic. I'm doing image processing using AWT and 2D. Images are stored in a RDBMS as BLOB Type, which I get using JDBC and convert to a BufferedImage using a JDBCImageDecoder. Now, I have my Buffe
-
HT6065 I installed this update and I no longer can access my AirPort Time Capsule via Finder
When I click on 'AirPort Time Capsule' in Finder, Finder crashes. I have hundreds of films on a USB drive connected to my AirPort Time Capsule and I no longer can access them on my home network.... Luckily AirPort Utiity still works and I could resta
-
you've seen the Apple photo of 3 different people video chating. We'll we've never been able to do it. Wife has ibook ppc with leopard, I have g4 tower ppc with tiger and niece has ibook intel with leopard. We ALL have latest builds of ALL Apple soft
-
Upgraded to Windows 7, lost all my itunes music and podcasts.
Lost all my stuff when i upgraded. Can I retrieve my preferences in the itunes store and recover the songs i had bought?
-
Revision: 11341 Author: [email protected] Date: 2009-10-30 16:24:35 -0700 (Fri, 30 Oct 2009) Log Message: Added some unit tests to get the metadata package above 80% Modified Paths: osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/metad