Accessing files of domain throw URL
Hi All,
I have a requirement i.e
Some files are there on the location */bea102/user_projects/domains/cms_domain/report/*.
I want to access those file throws Http URL.
How can I do this.
Please help me.
Regards
Arvind
Hi
if you want weblogic server to be able to serve files you have the following options
a. The files should be part of your web-app. This means physically copying the files to your webapp so that there are part of your EAR.
b. http://download.oracle.com/docs/cd/E13222_01/wls/docs100/webapp/weblogic_xml.html#wp1039396 - use the proprietary virtual directory mapping feature
c. Create a servlet that reads files from the file system
and as already suggested if these are static files and you have a webserver fronting weblogic then use that.
Note also that if you want to read from filesystems and you have a cluster , you will have to work out how files are shared
regards
deepak
Similar Messages
-
How do a client access the WAR file at loading a URL?
I would like to apprehend that how do a client access the WAR file at loading a URL?
Actually a web containter,for example,servlet container can have the software tool such as iPlanet[tm] Application server to deploying the servlet classes and JSP files by containing the WEB-INF directory.
how could the process of request and reponse be done by employing the WAR file..plz steer me....clients don't access a war file. that's just a package for the container to deal with.
when the WAR is deployed, the container unpackages the contents and deploys the app. From that point forward clients use the deployed stuff. the unpackaged servlets handle requests from then on.
your question makes little sense to me.
% -
Access wav-files in jar-archives (URL works, File works not)
Hi there!
The un-jar-ed application works fine, but I have a problem with accessing files in jar archives.
URL url = Classname.class.getResource("testdir/test.wav");works fine (and loading images works this way), but as soon as I try to get the file
File file = new File(url.getFile());I get an null-exception.
(in my case, I use the jmf package to play the sound-files, and I get the problem when I try to instatiate the MediaLocator
MediaLocator mediaLocator = new MediaLocator(url);but I think the problem is the same)
Thanx for helpworks fine Then keep doing it that way. What's the problem? It's true that you can't access something in a jar archive via a File object, so don't do that.
-
Accessing BSP File Download using HTTPS URL
Hi,
I'm struggling with a problem of downloading a file from a https url. I wrote a BSP App for downloading a file from a unix server.. It works fine when I use a http URL with port 8080 and does not work when I use https.!!
Example:
https://comms.gmsanet.co.za/supplier [ download does not work ]
http://comms.gmsanet.co.za:8080/supplier [ download works ]
When I try to download using https.. it does not pull the file name and path
see code below and suggest me if anything to be chnaged.
In the Form Initialization method:
event handler fr data retrieval
DATA: i_file type string,
s_fields TYPE tihttpnvp,
s_fields_line TYPE ihttpnvp,
multipart_form type ref to if_http_entity,
file_upload type xstring,
lv_backend type string,
success type string,
entity type ref to if_http_entity,
file type xstring,
content_type type string,
content_filename type string,
content_length type string,
content_disposition type string,
num_multiparts type i,
i type i value 1,
doEcho type string value 'X',
value type string,
filename type ZFILETAB-fileinfo,
ext1 type string,
ext2 type string,
dsn type string,
bptype like sy-uname,
itab TYPE ZFILETAB,
itab_line TYPE ZFILETABLINE,
file_ext type ZFILETABLINE,
fileinfo type c,
zcount type i.
filename = '/NewMessge.doc'.
content_filename = filename.
Check the extension and assign the content type
split filename at '.' into ext1 ext2.
case ext2.
when 'zip'.
content_type = 'application/x-zip-compressed'.
when 'doc'.
content_type = 'application/msword'.
when 'txt'.
content_type = 'text/plain'.
when 'ppt' or 'pps'.
content_type = 'application/vnd.ms-powerpoint'.
when 'xls' or 'exe'.
content_type = 'application/octet-stream'.
when 'gif'.
content_type = 'image/gif'.
when 'jpg' or 'jpeg'.
content_type = 'image/pjpeg'.
when 'htm' or 'html'.
content_type = 'text/html'.
endcase.
dsn = filename.
OPEN DATASET dsn FOR INPUT IN BINARY MODE.
IF sy-subrc NE 0.
zmessage = 'Error opening file'.
navigation->set_parameter( name = 'zmessage' value = zmessage ).
navigation->goto_page( 'downloaderror.htm' ).
exit.
ENDIF.
DO.
READ DATASET dsn INTO <b>file</b>.
EXIT.
ENDDO.
CLOSE DATASET dsn.
set response data to be the file content
runtime->server->response->set_data( <b>file</b> ).
runtime->server->response->set_header_field(
name = 'Content-Type'
value = content_type ).
concatenate 'attachment; filename=' filename into content_disposition.
runtime->server->response->set_header_field(
name = 'Content-Disposition'
value = content_disposition ).
set the file size in the response
content_length = xstrlen( file ).
runtime->server->response->set_header_field(
name = 'Content-Length'
value = content_length ).
runtime->server->response->delete_header_field(
name = 'Cache-Control' ).
runtime->server->response->delete_header_field(
name = 'Expires' ).
navigation->response_complete( ).
Thanks
AjayHi Brian,
I have the same problem as Ajay Yeluguri. In http mode I can generate a download of an Excel document but when we use the portal in https it doesn't work.
When I try to download using https it does not pull the file name and path and when I choose download I have a error message : "Internet Explorer cannot download from ..."
I've test the point 3.2 "... including file up/download" of the BSP application IT00 and it works fine in http and https mode. My problem is not the upload but the download. And in this application the uploaded document is opened in the Internet Explorer window but I want to generate a Save as... window to download the file.
Have you an idea what i can do to solve my problem.
Thanks
Yann -
Can not get access files from Windows 7 to Claims-based file authorization share
We have AD level 2012R2, DCs running 2012R2 of course, and we have clustered File Server (3 FSNodes running 2012R2).
We enabled 2 policies
KDC Support for claim
Kerberos support for claim
We created 1 claim type in ADAC (For example "Division" Source Property). Filled this property to all IT AD Accounts by our value "IT"
On FS made a share folder ITDivision:
- set permissions Domain Users can Modify if User.Division equals "IT"
so on Windows 8 IT Users can access files on this share and on Windows 7 they cant
=\ . We know from many presentations about Dynamic Access Control that File Server must enroll user claims if client do not support this claims (Service-for-User-To-Self)Hi,
>>so on Windows 8 IT Users can access files on this share and on Windows 7 they cant
=\ . We know from many presentations about Dynamic Access Control that File Server must enroll user claims if client do not support this claims (Service-for-User-To-Self)
How is it going? Was there any error message? As far as I know, Dynamic Access Control (DAC) should work for downlevel clients. It’s backwards compatible. As Florain explains in the following blog:
For non-Windows 8 and non-Windows Server 2012 boxes accessing DAC-protected file shares, the users do not carry any claims. For them, the Server 2012-based file share will query Active Directory and proxy the claims request to figure out what claims
the user and machine bring. The file server checks in the name of the user, whether they should have claims. With that information, the file server evaluates the access to the file share. So yeah – DAC works for downlevel clients, too. It’s backwards compatible.
And totally transparent to Windows 7.
Questions regarding Dynamic Access Control (FAQ)
http://www.frickelsoft.net/blog/?p=293
In addition, regarding dynamic access control, the following blog can also be referred to for more information.
Dynamic Access Control in Windows Server 2012
http://www.infoq.com/news/2012/10/Dynamic-Access-Control
Please Note: Since the above two website are not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
Best regards,
Frank Shen -
Cannot access file from JApplet
I have used the swingall.jar file with my JApplet for any
version of IE. It gives one error
i.e
Cannot access file c:\prog\project
I want to create a directory within c:\prog and also i want
to write some files there. Pls help me.try this my friend!
1. Compile the applet
2. Create a JAR file
3. Generate Keys
4. Sign the JAR file
5. Export the Public Key Certificate
6. Import the Certificate as a Trusted Certificate
7. Create the policy file
8. Run the applet
Susan
Susan bundles the applet executable in a JAR file, signs the JAR file, and exports the public key certificate.
1. Compile the Applet
In her working directory, Susan uses the javac command to compile the SignedAppletDemo.java class. The output from the javac command is the SignedAppletDemo.class.
javac SignedAppletDemo.java
2. Make a JAR File
Susan then makes the compiled SignedAppletDemo.class file into a JAR file. The -cvf option to the jar command creates a new archive (c), using verbose mode (v), and specifies the archive file name (f). The archive file name is SignedApplet.jar.
jar cvf SignedApplet.jar SignedAppletDemo.class
3. Generate Keys
Susan creates a keystore database named susanstore that has an entry for a newly generated public and private key pair with the public key in a certificate. A JAR file is signed with the private key of the creator of the JAR file and the signature is verified by the recipient of the JAR file with the public key in the pair. The certificate is a statement from the owner of the private key that the public key in the pair has a particular value so the person using the public key can be assured the public key is authentic. Public and private keys must already exist in the keystore database before jarsigner can be used to sign or verify the signature on a JAR file.
In her working directory, Susan creates a keystore database and generates the keys:
keytool -genkey -alias signFiles -keystore susanstore -keypass kpi135 -dname "cn=jones" -storepass ab987c
This keytool -genkey command invocation generates a key pair that is identified by the alias signFiles. Subsequent keytool command invocations use this alias and the key password (-keypass kpi135) to access the private key in the generated pair.
The generated key pair is stored in a keystore database called susanstore (-keystore susanstore) in the current directory, and accessed with the susanstore password (-storepass ab987c).
The -dname "cn=jones" option specifies an X.500 Distinguished Name with a commonName (cn) value. X.500 Distinguished Names identify entities for X.509 certificates.
You can view all keytool options and parameters by typing:
keytool -help
4. Sign the JAR File
JAR Signer is a command line tool for signing and verifying the signature on JAR files. In her working directory, Susan uses jarsigner to make a signed copy of the SignedApplet.jar file.
jarsigner -keystore susanstore -storepass ab987c -keypass kpi135 -signedjar SSignedApplet.jar SignedApplet.jar signFiles
The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
5. Export the Public Key Certificate
The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
The -storepass ab987c and -keystore susanstore options specify the keystore database and password where the private key for signing the JAR file is stored. The -keypass kpi135 option is the password to the private key, SSignedApplet.jar is the name of the signed JAR file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR file.
5: Export the Public Key Certificate
The public key certificate is sent with the JAR file to the whoever is going to use the applet. That person uses the certificate to authenticate the signature on the JAR file. To send a certificate, you have to first export it.
In her working directory, Susan uses keytool to copy the certificate from susanstore to a file named SusanJones.cer as follows:
keytool -export -keystore susanstore -storepass ab987c -alias signFiles -file SusanJones.cer
Ray
Ray receives the JAR file from Susan, imports the certificate, creates a policy file granting the applet access, and runs the applet.
6. Import Certificate as a Trusted Certificate
Ray has received SSignedApplet.jar and SusanJones.cer from Susan. He puts them in his home directory. Ray must now create a keystore database (raystore) and import the certificate into it. Ray uses keytool in his home directory /home/ray to import the certificate:
keytool -import -alias susan -file SusanJones.cer -keystore raystore -storepass abcdefgh
7. Create the Policy File
The policy file grants the SSignedApplet.jar file signed by the alias susan permission to create newfile (and no other file) in the user's home directory.
Ray creates the policy file in his home directory using either policytool or an ASCII editor.
keystore "/home/ray/raystore";
// A sample policy file that lets a JavaTM program
// create newfile in user's home directory
// Satya N Dodda
grant SignedBy "susan"
permission java.security.AllPermission;
8. Run the Applet in Applet Viewer
Applet Viewer connects to the HTML documents and resources specified in the call to appletviewer, and displays the applet in its own window. To run the example, Ray copies the signed JAR file and HTML file to /home/aURL/public_html and invokes Applet viewer from his home directory as follows:
Html code :
</body>
</html>
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width="600" height="400" align="middle"
codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,1,2">
<PARAM NAME="code" VALUE="SignedAppletDemo.class">
<PARAM NAME="archive" VALUE="SSignedApplet.jar">
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
</OBJECT>
</body>
</html>
appletviewer -J-Djava.security.policy=Write.jp
http://aURL.com/SignedApplet.html
Note: Type everything on one line and put a space after Write.jp
The -J-Djava.security.policy=Write.jp option tells Applet Viewer to run the applet referenced in the SignedApplet.html file with the Write.jp policy file.
Note: The Policy file can be stored on a server and specified in the appletviewer invocation as a URL.
9. Run the Applet in Browser
Download JRE 1.3 from Javasoft
save this to write.jp
keystore "/home/ray/raystore";
// A sample policy file that lets a JavaTM program
// create newfile in user's home directory
// Satya N Dodda
grant {
permission java.security.AllPermission;
save this to signedAppletDemo.java
* File: @(#)SignedAppletDemo.java 1.1
* Comment: Signed Applet Demo
* @(#)author: Satya Dodda
* @(#)version: 1.1
* @(#)date: 98/10/01
import java.applet.Applet;
import java.awt.Graphics;
import java.io.*;
import java.awt.Color;
* A simple Signed Applet Demo
public class SignedAppletDemo extends Applet {
public String test() {
setBackground(Color.white);
System.out.println(System.getProperty("user.home"));
String fileName = System.getProperty("user.home") +
System.getProperty("file.separator") +
"newfile";
String msg = "This message was written by a signed applet!!!\n";
String s ;
try {
FileWriter fos = new FileWriter(fileName);
fos.write(msg, 0, msg.length());
fos.close();
s = new String("Successfully created file :" + fileName);
} catch (Exception e) {
System.out.println("Exception e = " + e);
e.printStackTrace();
s = new String("Unable to create file : " + fileName);
return s;
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawString("Signed Applet Demo", 120, 50);
g.setColor(Color.magenta);
g.drawString(test(), 50, 100); -
Unable to export data from Web Access Data Sheet in Sharepoint to local excel or access file
Greetings and good morning.
I'm going to start off in broad terms with this question because I'm not 100 percent sure what information to provide.
Long story short, we've got a Web Access Data Sheet list hosted in a Sharepoint 2010 environment. It is accessed and used by multiple people throughout the day. It contains several thousand line item entries. I'd call it a large data sheet.
I think the size of the data sheet is casuign some instability in the list. I'd like to be able to export a defined range of data from the list into a local excel or access file. After that, I'd delete the stuff on the Access list to improve performance.
But...when I attempt to use the Sharepoint Action bar to export - Excel locks up/crashes. If I try to export to Access, I get a similar issue.
Any ideas? Could anyone begin by telling me what other information is required?Hi,
If you would like to export data from Access Web Database in SharePoint 2010, you could go to Design With Access page in Settings. The url in my environment is http://sp/tt/_layouts/accsrv/ModifyApplication.aspx . Then choose the Table and export it to Excel
or Modify it in Access.
Regards,
Rebecca Tu
TechNet Community Support -
Scenario
Windows 7 users log on to workstations at a site. Domain Controller is up and does the domain authentication for those users across the WAN. Users are then accessing a local(same building) Shared directory on a Windows 2008r2 server, in order to open, modify,
save new files, etc.
Then, the site loses access to the Domain Controller due to a WAN outage.
Question
Will those users that have already logged onto their Windows 7 workstations continue to have access to the shared resources on the local Windows 2008r2 server with their cached credentials(assuming they don't logoff or restart their machines)?? This has
been the case in the past, but wondering if anything has changed with Windows 2008??
ThanksHi,
The duration that you can access the server depends on when the server requires re-authentication.
In Windows implementation, SMB session expiration is enforced based upon the client’s support of dynamic re-authentication capability [MS-SMB].
If the client enables the CAP_DYNAMIC_REAUTH capability bit, the server will enforce session expiration. If a client does not set CAP_DYNAMIC_REAUTH, the Windows server does not return STATUS_NETWORK_SESSION_EXPIRED.
The SMB dynamic re-authentication feature was introduced in Windows XP. From there, Windows-based clients set the CAP_DYNAMIC_REAUTH capability bit to indicate to the server that the client supports re-authentication when the Kerberos service ticket for
the session expires.
Windows servers do check CAP_DYNAMIC_REAUTH:
If clientCapabilities sets CAP_DYNAMIC_REAUTH, the server will set Server. Session.AuthenticationExpirationTime to the expiry time returned by AcceptSecuirtyContext.
If clientCapabilities does not set CAP_DYNAMIC_REAUTH, the server will not set Server. Session.AuthenticationExpirationTime, basically a CAP_DYNAMIC_REAUTH capability bit not set by the client means the session will not expire on the server side.
To configure Maximum lifetime for service ticket, you can use grouppolicy. The default value of
Maximum lifetime for service ticket
in Default Domain Policy is 600 minutes.
Note:This setting is applied to DC, not clients.
For detailed information, please view the link below
CIFS and SMB Timeouts in Windows
http://blogs.msdn.com/b/openspecification/archive/2013/03/19/cifs-and-smb-timeouts-in-windows.aspx
Maximum lifetime for service ticket
http://technet.microsoft.com/en-us/library/jj852188.aspx
Hope this helps.
Steven Lee
TechNet Community Support -
Unable to access files with spaces in the path
Hi all, I am accessing files which reside on the server using a java applet.
The typical path of a file could be:
http://192.168.0.2/agat/data/AF190701 0003.agt
(not the space in the filename).
When I try to open this file using a URL object:
URL file = new URL(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(file.openStream()));
I get exception 400 ( I think) whihc I assume is file cant be found.
However when I rename the file (to get rid of that space) and also change the filename variable to suit. The file is opened as expected.
What should I do to make the applet able to open paths with spaces? Or is this just not possible.
I did try including quotes with the special characte precessor:
filename = "/"http://192.168.0.2/agat/data/AF190701 0003.agt/""
But this didnt work either, please could someone tell what I need.
Thanks.Thanks guys, although before I got your replies I did the following - it seems to work, but shall try your suggestions.
while (file.lastIndexOf(" ") >0)
String temp;
int num = file.lastIndexOf(" ");
temp = file.substring(0, num) + "%20" + file.substring(num+1, file.length());
file = temp;
} -
Error accessing file template file not found (error code 2)
We have 3 admins that work on the website so we use the Check In/ Check Out feature of DW. We all have DW CS6.
When I update the template I have no problem (I work on a mac). However, if one of the other admins (Windows) tries he gets the following message: Error accessing file template file "C:\filepath\filename.dwt": file not found (error code 2).
I looked at this thread: Re: Dreamweaver Template not updating pages error code 2? but the only solution offered there is to change the template tag from <!-- InstanceBegin... to <!-- TemplateBegin... If this is the solution, how do you do this?
When I go to the url of the template http://www.christophorushouse.com.au/Templates/chrv-main-template.dwt it says it's been (re)moved or renamed, but then I have a feeling you can't view/access a template this way. All pages of the website feed of this template.
Any help would be appreciated.
ThanksWe have 3 admins that work on the website so we use the Check In/ Check Out feature of DW. We all have DW CS6.
When I update the template I have no problem (I work on a mac). However, if one of the other admins (Windows) tries he gets the following message: Error accessing file template file "C:\filepath\filename.dwt": file not found (error code 2).
I looked at this thread: Re: Dreamweaver Template not updating pages error code 2? but the only solution offered there is to change the template tag from <!-- InstanceBegin... to <!-- TemplateBegin... If this is the solution, how do you do this?
When I go to the url of the template http://www.christophorushouse.com.au/Templates/chrv-main-template.dwt it says it's been (re)moved or renamed, but then I have a feeling you can't view/access a template this way. All pages of the website feed of this template.
Any help would be appreciated.
Thanks -
Website from BETA now down and can no longer access files!
I created two sites while Muse was in Beta. They are now both down and giving the error message: NO START PAGE: Could not display this Web Site as no Start Page has been configured. To configure a default starting page, set one of your Web Pages to be the Start Page. Please contact your Administrator for more information. I can't access the files anymore because both Muse and BC are different.
My clients are very angry and I have tried everything, even creating a new site but I can not use the domain because it has the same servers and continues to go to the old site that I can not access. The domains are www.renovatingdetroit.com and www.ariasalongp.com.
Any help would be appreciated since there is business involved I will start losing money very quickly if I can not get the sites back up and running.Hi Brandon,
Both the sites http://www.renovatingdetroit.com and http://www.ariasalongp.com are live at the moment.
Please check the screenshots I took a moment ago:
http://flashfiredesign.businesscatalyst.com/FTP/ariasalongp.png
http://flashfiredesign.businesscatalyst.com/FTP/renovatingdetroit.png
It seems there was an issue with the payment which has been cleared today itself. Can you please confirm?
Thanks,
Vikas -
How to get the target file name from an URL?
Hi there,
I am trying to download data from an URL and save the content in a file that have the same name as the file on the server. In some way, what I want to do is pretty similar to what you can do when you do a right click on a link in Internet Explorer (or any other web browser) and choose "save target as".
If the URL is a direct link to the file (for example: http://java.sun.com/images/e8_java_logo_red.jpg ), I do not have any problem:
URL url = new URL("http://java.sun.com/images/e8_java_logo_red.jpg");
System.out.println("Opening connection to " + url + "...");
// Copy resource to local file
InputStream is = url.openStream();
FileOutputStream fos=null;
String fileName = null;
StringTokenizer st=new StringTokenizer(url.getFile(), "/");
while (st.hasMoreTokens())
fileName=st.nextToken();
System.out.println("The file name will be: " + fileName);
File localFile= new File(System.getProperty("user.dir"), fileName);
fos = new FileOutputStream(localFile);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) != -1) {
fos.write(buf, 0, i);
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (is != null)
is.close();
if (fos != null)
fos.close();
}Everything is fine, the file name I get is "e8_java_logo_red.jpg", which is what I expect to get.
However, if the URL is an indirect link to the file (for example: http://javadl.sun.com/webapps/download/AutoDL?BundleId=37719 , which link to a file named JavaSetup6u18-rv.exe ), the similar code return AutoDL?BundleId=37719 as file name, when I would like to have JavaSetup6u18-rv.exe .
URL url = new URL("http://javadl.sun.com/webapps/download/AutoDL?BundleId=37719");
System.out.println("Opening connection to " + url + "...");
// Copy resource to local file
InputStream is = url.openStream();
FileOutputStream fos=null;
String fileName = null;
StringTokenizer st=new StringTokenizer(url.getFile(), "/");
while (st.hasMoreTokens())
fileName=st.nextToken();
System.out.println("The file name will be: " + fileName);
File localFile= new File(System.getProperty("user.dir"), fileName);
fos = new FileOutputStream(localFile);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) != -1) {
fos.write(buf, 0, i);
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (is != null)
is.close();
if (fos != null)
fos.close();
}Do you know how I can do that.
Thanks for your help
// JB
Edited by: jb-from-sydney on Feb 9, 2010 10:37 PMThanks for your answer.
By following your idea, I found out that one of the header ( content-disposition ) can contain the name to be used if the file is downloaded. Here is the full code that allow you to download locally a file on the Internet:
* Download locally a file from a given URL.
* @param url - the url.
* @param destinationFolder - The destination folder.
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
public static final File downloadFile(URL url, File destinationFolder) throws IOException {
URLConnection urlC = url.openConnection();
InputStream is = urlC.getInputStream();
FileOutputStream fos = null;
String fileName = getFileName(urlC);
destinationFolder.mkdirs();
File localFile = new File(destinationFolder, fileName);
fos = new FileOutputStream(localFile);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) != -1) {
fos.write(buf, 0, i);
} finally {
if (is != null)
is.close();
if (fos != null)
fos.close();
return localFile;
* Returns the file name associated to an url connection.<br />
* The result is not a path but just a file name.
* @param urlC - the url connection
* @return the file name
* @throws IOException Signals that an I/O exception has occurred.
private static final String getFileName(URLConnection urlC) throws IOException {
String fileName = null;
String contentDisposition = urlC.getHeaderField("content-disposition");
if (contentDisposition != null) {
fileName = extractFileNameFromContentDisposition(contentDisposition);
// if the file name cannot be extracted from the content-disposition
// header, using the url.getFilename() method
if (fileName == null) {
StringTokenizer st = new StringTokenizer(urlC.getURL().getFile(), "/");
while (st.hasMoreTokens())
fileName = st.nextToken();
return fileName;
* Extract the file name from the content disposition header.
* <p>
* See <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html">http:
* //www.w3.org/Protocols/rfc2616/rfc2616-sec19.html</a> for detailled
* information regarding the headers in HTML.
* @param contentDisposition - the content-disposition header. Cannot be
* <code>null>/code>.
* @return the file name, or <code>null</code> if the content-disposition
* header does not contain the filename attribute.
private static final String extractFileNameFromContentDisposition(
String contentDisposition) {
String[] attributes = contentDisposition.split(";");
for (String a : attributes) {
if (a.toLowerCase().contains("filename")) {
// The attribute is the file name. The filename is between
// quotes.
return a.substring(a.indexOf('\"') + 1, a.lastIndexOf('\"'));
// not found
return null;
} -
Accessing file shares from JSP
Hi,
I need to be able to access file shares from a JSP page. Here's the JSP code:
<%@ page language="java" %>
<%@ page import="java.io.*" %>
<%@ page errorPage="errorPage.jsp" %>
<%
String fileSystemPath = "\\\\130.26.1.199\\MeetingManager30\\test.txt";
File f = new File(fileSystemPath);
f.createNewFile();
%>The above code resides in a server with IP 130.9.68.6 and is deployed onto the Tomcat on the server.
When I tried to run the above code, I got this error
java.io.IOException: Access is denied at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:827) at org.apache.jsp.test_jsp._jspService
(test_jsp.java:55) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at org.apache.jasper.servlet.JspServletWrapper.service
(JspServletWrapper.java:210) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.StandardWrapperValve.invoke
(StandardWrapperValve.java:256) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:191) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2422) at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invok
eNext(StandardPipeline.java:643) at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:163)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:174) at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:199) at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:833) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processCon
nection(Http11Protocol.java:711) at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:584) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run
(ThreadPool.java:687) at java.lang.Thread.run(Thread.java:536) Seems like I'm having a system level security setting problem here.
I know it's a security issue, because I've encountered the equivalent problem in ASP/IIS, and I had to give a domain user rights to both the IIS Virtual Directory, and the file share to be able to access.
Any ideas how to set up Tomcat to be able to access the file share successfully?
Thanks in advance!Hello Veer,
From what you have posted it looks like while logging your error another problem occurred. Did you get any output from your System.out calls? If not can you try adding a few in order to home in the problem area.
Hussein Badakhchani
www.orbism.com -
This program is supposed to retrieve data from TelephoneUI's JTextFields, store the data in a RandomAccessRecord class object record and call the write method of class RandomAccessRecord to output the data.
Two questions
Is there any way to check if the data was actually written to the file without writing a new class to read the file?
How can I make it so that the file-position pointer for object output start from byte 0 for the first record and move 94 bytes after each read? Right now the file-position pointer moves 94 bytes after each read but starts from 94.
public class WriteRandomFile extends JFrame {
private RandomAccessFile output;
private TelephoneUI userInterface;
private JButton enterButton, openButton;
// set up GUI
public WriteRandomFile()
super( "Write to random access file" );
// create instance of reusable user interface TelephoneUI
userInterface = new TelephoneUI(4); // four textfields
getContentPane().add( userInterface,
BorderLayout.CENTER );
// get reference to generic task button doTask1 in TelephoneUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open..." );
// register listener to call openFile when button pressed
openButton.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// allow user to select file to open
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// add record in TelephoneUI, then close file
public void windowClosing( WindowEvent event )
if ( output != null )
addRecord();
closeFile();
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2 in TelephoneUI
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false );
// register listener to call addRecord when button pressed
enterButton.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// add record to file
public void actionPerformed( ActionEvent event )
addRecord();
} // end anonymous inner class
); // end call to addActionListener
setSize( 300, 150 );
show();
// enable user to choose file to open
private void openFile()
// display file dialog so user can select file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File Name",
JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new RandomAccessFile( fileName, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
// process exception while opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
} // end method openFile
// close file and terminate application
private void closeFile()
// close file and exit
try {
if ( output != null )
output.close();
System.exit( 0 );
// process exception while closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
// add one record to file
public void addRecord()
String fields[] = userInterface.getFieldValues();
RandomAccessRecord record =
new RandomAccessRecord();
int count = 1;
// ensure field has a value
if ( ! fields[ TelephoneUI.LASTNAME ].equals( "" ) ) {
// output values to file
try {
record.setFirstName( fields[ TelephoneUI.FIRSTNAME ] );
record.setLastName( fields[ TelephoneUI.LASTNAME ] );
record.setAddress( fields[ TelephoneUI.ADDRESS ] );
record.setPhone( Integer.parseInt( fields[ TelephoneUI.PHONENUMBER ] ) );
count = count * 94;
output.seek( count );
record.write( output );
userInterface.clearFields(); // clear TextFields
// process improper account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions while writing to file
catch ( IOException ioException ) {
closeFile();
} // end method addRecord
// execute application
public static void main( String args[] )
new WriteRandomFile();
} // end class WriteRandomFileThis program is supposed to retrieve data from
TelephoneUI's JTextFields, store the data in a
RandomAccessRecord class object record and call the
write method of class RandomAccessRecord to output
the data.
Two questions
Is there any way to check if the data was actually
written to the file without writing a new class to
read the file? Why? If the io operations are not working (and not throwing exceptions) then you might as well give up.
>
How can I make it so that the file-position pointer
for object output start from byte 0 for the first
record and move 94 bytes after each read? Right now
the file-position pointer moves 94 bytes after each
read but starts from 94.Huh? It moves 94 and you want it to move 94?
Perhaps you are just looking for the getFilePointer() and seek() methods?
>
public class WriteRandomFile extends JFrame {
private RandomAccessFile output;
private TelephoneUI userInterface;
private JButton enterButton, openButton;
// set up GUI
public WriteRandomFile()
super( "Write to random access file" );
// create instance of reusable user interface
erface TelephoneUI
userInterface = new TelephoneUI(4); // four
/ four textfields
getContentPane().add( userInterface,
BorderLayout.CENTER );
// get reference to generic task button doTask1
oTask1 in TelephoneUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open..." );
// register listener to call openFile when
e when button pressed
openButton.addActionListener(
// anonymous inner class to handle
to handle openButton event
new ActionListener() {
// allow user to select file to open
public void actionPerformed( ActionEvent
ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing
losing event
addWindowListener(
// anonymous inner class to handle
to handle windowClosing event
new WindowAdapter() {
// add record in TelephoneUI, then close
, then close file
public void windowClosing( WindowEvent
WindowEvent event )
if ( output != null )
addRecord();
closeFile();
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2
oTask2 in TelephoneUI
enterButton =
tton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false );
// register listener to call addRecord when
d when button pressed
enterButton.addActionListener(
// anonymous inner class to handle
to handle enterButton event
new ActionListener() {
// add record to file
public void actionPerformed( ActionEvent
ActionEvent event )
addRecord();
} // end anonymous inner class
); // end call to addActionListener
setSize( 300, 150 );
show();
// enable user to choose file to open
private void openFile()
// display file dialog so user can select file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this
( this );
// if user clicked Cancel button on dialog,
ialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File
Invalid File Name",
JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new RandomAccessFile( fileName,
e( fileName, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
// process exception while opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
} // end method openFile
// close file and terminate application
private void closeFile()
// close file and exit
try {
if ( output != null )
output.close();
System.exit( 0 );
// process exception while closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
// add one record to file
public void addRecord()
String fields[] =
ds[] = userInterface.getFieldValues();
RandomAccessRecord record =
new RandomAccessRecord();
int count = 1;
// ensure field has a value
if ( ! fields[ TelephoneUI.LASTNAME ].equals(
quals( "" ) ) {
// output values to file
try {
record.setFirstName( fields[
stName( fields[ TelephoneUI.FIRSTNAME ] );
record.setLastName( fields[
stName( fields[ TelephoneUI.LASTNAME ] );
record.setAddress( fields[
ddress( fields[ TelephoneUI.ADDRESS ] );
record.setPhone( Integer.parseInt(
teger.parseInt( fields[ TelephoneUI.PHONENUMBER ] )
count = count * 94;
output.seek( count );
record.write( output );
userInterface.clearFields(); // clear
); // clear TextFields
// process improper account number or
number or balance format
catch ( NumberFormatException
Exception formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions while writing to file
catch ( IOException ioException ) {
closeFile();
} // end method addRecord
// execute application
public static void main( String args[] )
new WriteRandomFile();
} // end class WriteRandomFile -
Modify Record Number in a Random Access File
Hi Does anyone know if I can modify the record number in the random access file hardware.dat for each hardware record each time and update it in hardware.dat to display it? Also why does it say "Record does not exist" if I modify the record number for a hardware and try to update it but could not find that record?
Here is the code below:
// Exercise 14.11: HardwareRecord.java
package org.egan; // packaged for reuse
public class HardwareRecord
private int recordNumber;
private String toolName;
private int quantity;
private double cost;
// no-argument constructor calls other constructor with default values
public HardwareRecord()
this(0,"",0,0.0); // call four-argument constructor
} // end no-argument HardwareRecord constructor
// initialize a record
public HardwareRecord(int number, String tool, int amount, double price)
setRecordNumber(number);
setToolName(tool);
setQuantity(amount);
setCost(price);
} // end four-argument HardwareRecord constructor
// set record number
public void setRecordNumber(int number)
recordNumber = number;
} // end method setRecordNumber
// get record number
public int getRecordNumber()
return recordNumber;
} // end method getRecordNumber
// set tool name
public void setToolName(String tool)
toolName = tool;
} // end method setToolName
// get tool name
public String getToolName()
return toolName;
} // end method getToolName
// set quantity
public void setQuantity(int amount)
quantity = amount;
} // end method setQuantity
// get quantity
public int getQuantity()
return quantity;
} // end method getQuantity
// set cost
public void setCost(double price)
cost = price;
} // end method setCost
// get cost
public double getCost()
return cost;
} // end method getCost
} // end class HardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: RandomAccessHardwareRecord.java
// Subclass of HardwareRecord for random-access file programs.
package org.egan; // package for reuse
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessHardwareRecord extends HardwareRecord
public static final int SIZE = 46;
// no-argument constructor calls other constructor with default values
public RandomAccessHardwareRecord()
this(0,"",0,0.0);
} // end no-argument RandomAccessHardwareRecord constructor
// initialize a RandomAccessHardwareRecord
public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
super(number,tool,amount,price);
} // end four-argument RandomAccessHardwareRecord constructor
// read a record from a specified RandomAccessFile
public void read(RandomAccessFile file) throws IOException
setRecordNumber(file.readInt());
setToolName(readName(file));
setQuantity(file.readInt());
setCost(file.readDouble());
} // end method read
// ensure that name is proper length
private String readName(RandomAccessFile file) throws IOException
char name[] = new char[15], temp;
for(int count = 0; count < name.length; count++)
temp = file.readChar();
name[count] = temp;
} // end for
return new String(name).replace('\0',' ');
} // end method readName
// write a record to specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
file.writeInt(getRecordNumber());
writeName(file, getToolName());
file.writeInt(getQuantity());
file.writeDouble(getCost());
} // end method write
// write a name to file; maximum of 15 characters
private void writeName(RandomAccessFile file, String name) throws IOException
StringBuffer buffer = null;
if (name != null)
buffer = new StringBuffer(name);
else
buffer = new StringBuffer(15);
buffer.setLength(15);
file.writeChars(buffer.toString());
} // end method writeName
} // end RandomAccessHardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFile.java
// creates random-access file by writing 100 empty records to disk.
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class CreateRandomFile
private static final int NUMBER_RECORDS = 100;
// enable user to select file to open
public void createFile()
RandomAccessFile file = null;
try // open file for reading and writing
file = new RandomAccessFile("hardware.dat","rw");
RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
// write 100 blank records
for (int count = 0; count < NUMBER_RECORDS; count++)
blankRecord.write(file);
// display message that file was created
System.out.println("Created file hardware.dat.");
System.exit(0); // terminate program
} // end try
catch (IOException ioException)
System.err.println("Error processing file.");
System.exit(1);
} // end catch
finally
try
if (file != null)
file.close(); // close file
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end finally
} // end method createFile
} // end class CreateRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFileTest.java
// Testing class CreateRandomFile
public class CreateRandomFileTest
// main method begins program execution
public static void main( String args[] )
CreateRandomFile application = new CreateRandomFile();
application.createFile();
} // end main
} // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: MenuOption.java
// Defines an enum type for the hardware credit inquiry program's options.
public enum MenuOption
// declare contents of enum type
PRINT(1),
UPDATE(2),
NEW(3),
DELETE(4),
END(5);
private final int value; // current menu option
MenuOption(int valueOption)
value = valueOption;
} // end MenuOptions enum constructor
public int getValue()
return value;
} // end method getValue
} // end enum MenuOption-------------------------------------------------------------------------------------------------
// Exercise 14.11: FileEditor.java
// This class declares methods that manipulate hardware account records
// in a random access file.
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class FileEditor
RandomAccessFile file; // reference to the file
Scanner input = new Scanner(System.in);
// open the file
public FileEditor(String fileName) throws IOException
file = new RandomAccessFile(fileName, "rw");
} // end FileEditor constructor
// close the file
public void closeFile() throws IOException
if (file != null)
file.close();
} // end method closeFile
// get a record from the file
public RandomAccessHardwareRecord getRecord(int recordNumber)
throws IllegalArgumentException, NumberFormatException, IOException
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
if (recordNumber < 1 || recordNumber > 100)
throw new IllegalArgumentException("Out of range");
// seek appropriate record in a file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.read(file);
return record;
} // end method getRecord
// update record tool name in file
public void updateRecordToolName(int recordNumber, String newToolName)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setToolName(newToolName);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordToolName
// update record in file
public void updateRecordQuantity(int recordNumber, int newQuantity)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setQuantity(newQuantity);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordQuantity
// update record in file
public void updateRecordCost(int recordNumber, double newCost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setCost(newCost);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordCost
// add record to file
public void newRecord(int recordNumber, String toolName, int quantity, double cost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() != 0)
throw new IllegalArgumentException("Record already exists");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record = new RandomAccessHardwareRecord(recordNumber, toolName, quantity, cost);
record.write(file); // write record to file
} // end method newRecord
// delete record from file
public void deleteRecord(int recordNumber) throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Account does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
// create a blank record to write to the file
record = new RandomAccessHardwareRecord();
record.write(file);
} // end method deleteRecord
// read and display records
public void readRecords()
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
try // read a record and display
file.seek(0);
while (true)
do
record.read(file);
while (record.getRecordNumber() == 0);
// display record contents
System.out.printf("%-10d%-15s%-15d%10.2f\n",record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end while
} // end try
catch (EOFException eofException) // close file
return; // end of file was reached
} // end catch
catch (IOException ioException)
System.err.println("Error reading file.");
System.exit(1);
} // end catch
} // end method readRecords
} // end class FileEditor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessor.java
// A transaction processing program using random-access files.
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class TransactionProcessor
private FileEditor dataFile;
private RandomAccessHardwareRecord record;
private MenuOption choices[] = {MenuOption.PRINT, MenuOption.UPDATE, MenuOption.NEW,
MenuOption.DELETE, MenuOption.END};
private Scanner input = new Scanner(System.in);
// get the file name and open the file
private boolean openFile()
try // attempt to open file
// call the helper method to open the file
dataFile = new FileEditor("hardware.dat");
} // end try
catch (IOException ioException)
System.err.println("Error opening file.");
return false;
} // end catch
return true;
} // end method openFile
// close file and terminate application
private void closeFile()
try // close file
dataFile.closeFile();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
// create, update or delete the record
private void performAction(MenuOption action)
int recordNumber = 0; // record number of record
String toolName; // tool name of the hardware instrument
int quantity; // total amount of items
double cost; // hareware tool price
int choice; // choose an update option
int newRecordNumber; // the updated record number
String newToolName; // the updated tool name
int newQuantity; // the updated quantity
double newCost; // the updated cost
try // attempt to manipulate files based on option selected
switch(action) // switch based on option selected
case PRINT:
System.out.println();
dataFile.readRecords();
break;
case NEW:
System.out.printf("\n%s%s\n%s\n%s","Enter record number,",
"tool name, quantity, and cost.","(Record number must be 1 - 100)","? ");
recordNumber = input.nextInt(); // read record number
toolName = input.next(); // read tool name
quantity = input.nextInt(); // read quantity
cost = input.nextDouble(); // read cost
dataFile.newRecord(recordNumber, toolName, quantity, cost); // create new record
break;
case UPDATE:
System.out.print("\nEnter record number to update (1 - 100): ");
recordNumber = input.nextInt();
record = dataFile.getRecord(recordNumber);
if (record.getRecordNumber() == 0)
System.out.println("Record does not exist.");
else
// display record contents
System.out.printf("%-10d%-12s%-12d%10.2f\n\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
System.out.printf("%s%s","\nEnter 1 to update tool name, ",
"2 to update quantity, or 3 to update cost : ");
choice = input.nextInt();
if (choice == 1)
System.out.print("Enter new record tool name : ");
newToolName = input.next();
dataFile.updateRecordToolName(recordNumber,newToolName); // update record
// tool name
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 2)
System.out.print("Enter new record quantity : ");
newQuantity = input.nextInt();
dataFile.updateRecordQuantity(recordNumber,newQuantity); // update record
// quantity
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 3)
System.out.print("Enter new record cost : ");
newCost = input.nextDouble();
dataFile.updateRecordCost(recordNumber,newCost); // update record cost
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end else
break;
case DELETE:
System.out.print("\nEnter an account to delete ( 1 - 100): ");
recordNumber = input.nextInt();
dataFile.deleteRecord(recordNumber); // delete record
break;
default:
System.out.println("Invalid action.");
break;
} // end switch
} // end try
catch (NumberFormatException format)
System.err.println("Bad input.");
} // end catch
catch (IllegalArgumentException badRecord)
System.err.println(badRecord.getMessage());
} // end catch
catch (IOException ioException)
System.err.println("Error writing to the file.");
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input.nextLine();
} // end catch
} // end method performAction
// enable user to input menu choice
private MenuOption enterChoice()
int menuChoice = 1;
// display available options
System.out.printf("\n%s\n%s\n%s\n%s\n%s\n%s","Enter your choice",
"1 - List hardware records", "2 - Update a hardware record",
"3 - Add a new hardware record", "4 - Delete a hardware record", "5 - End program\n?");
try
menuChoice = input.nextInt();
catch (NoSuchElementException elementException)
System.err.println("Invalid input.");
System.exit(1);
} // end catch
return choices[menuChoice - 1]; // return choice from user
} // end enterChoice
public void processRequests()
openFile();
// get user's request
MenuOption choice = enterChoice();
while (choice != MenuOption.END)
performAction(choice);
choice = enterChoice();
} // end while
closeFile();
} // end method processRequests
} // end class TransactionProcessor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessorTest.java
// Testing the transaction processor.
public class TransactionProcessorTest
public static void main(String args[])
TransactionProcessor application = new TransactionProcessor();
application.processRequests();
} // end main
} // end class TransactionProcessorTest-------------------------------------------------------------------------------------------------
Below is the sample data to be entered into the random input file hardware.dat :
Record Tool Quantity Cost
Number Name
3 Sander 18 35.99
19 Hammer 128 10.00
26 Jigsaw 16 14.25
39 Mower 10 79.50
56 Saw 8 89.99
76 Screwdriver 236 4.99
81 Sledgehammer 32 19.75
88 Wrench 65 6.48Message was edited by:
egan128
Message was edited by:
egan128
Message was edited by:
egan128Hi Does anyone know if I can modify the record number
in the random access file hardware.dat for each
hardware record each time and update it in
hardware.dat to display it?If the "record number" is data that is stored in the file, then you can modify it. More precisely: it is possible to modify it.
The rest of the question had too many incompatible verbs for me to understand it.
Also why does it say
"Record does not exist" if I modify the record number
for a hardware and try to update it but could not
find that record?"Record does not exist" is a fairly reasonable error message for the situation where a program looks for a record but cannot find it. Are you asking why that particular lump of code actually does that?
(One thousand lines of code removed)
Maybe you are looking for
-
Oracle 8iLite / Oracle Developer 6.0
I would like to know if it is possible to install and run Oracle 8iLite and Oracke Developer 6.0. In other words I would like to connect to a local database using Oracle Developer 6.0.
-
ABAP Client Proxy error code: 401, error text: Unauthorized
Hi, I have Client proxy in ECC for oubound interface in PI 7.0, when i look into SXMB_MONI of ECC i can see my message with Error "HTTP response contains status code 401 with the description Unauthorized Authorization error while sending by HTTP (err
-
Error when passing parameters in a link
Hi: i have a report and a form. i've created a link that will point to the form from the report. So i've associated the link to a field of the report and edited it so that a key field in the form will be equal to a value passed from the report's key
-
Ah! I accidently deleted a Dock Icon. How do I get it back?
I just deleted the icon that comes as a default (I guess) and its right next to the trash icon and it starts up the Mac OS X Website. It looks like a little slinky, coil, or spring and its silver. Oh man...I don't know where it went! How can I get it
-
About listener mistake,please help me!!
I installed oracle10g on RHEL4 successfuly(ship.db.lnx32.cpio).But I get errors when I execute lsnrctl: [oracle@biodb1 product]$ lsnrctl LSNRCTL for Linux: Version 10.1.0.3.0 - Production on 09-MAR-2006 15:01:56 Copyright (c) 1991, 2004, Oracle. All