Generating a random include file
I'm trying to generate a random "include" file in an HTML web page. I have a group of 20 files, each with one sentence, and I'd like to randomly call one of those files into my web page, using a statement like
<!--include virtual = "includes/file1.inc" -->
Is there a way to use Javascript to generate that line of code, but make the number just before ".inc" be randomly entered?
Thanks in advance.
Bob
Well, dynamically formed file name for include is not possible in javasript. Includes are processed before any javascript runs on the page.
But
You can do this if you keep the lines in the HTML file:
<SCRIPT LANGUAGE="JavaScript">
lines = new Array;
lines[1] = "Well, some things in Javascript are not cool";
lines[2] = "Sometimes Javascript is cool";
lines[3] = "Ok, I am getting tired of typing now";
lines[4] = "But then again, who is worried";
lines[5] = "A random line can be shown";
var total = 5;
var randomNumber = Math.random();
var idx = Math.round( (total-1) * randomNumber) + 1;
document.write(lines[idx]);
</SCRIPT>
Similar Messages
-
Stop xjc generating entire include file
I have defined a whole bunch of elements in a schema (m_fields.xsd). Another schema (myclass.xsd) uses an <xsd:include> to include m_fields and points to some of its fields (using ref="m_fields fieldname").
My problem is this : when I use xjc.bat to generate a class out of myclass.xsd it generates objects for ALL the fields defined in the included file m_fields.xsd. Is there a way to stop this happening ?So that means that if you're generating with JAXB you're more or less limited to "standalone" classes, each with a one on one relationship with a schema.
If I'm right that's a pity; I'm generating data container objects out of schemas for a large organisation and many of the fields I'm using in these classes are common ones.
Is there any other way around this or am I indeed limited to defining a set of types for each data container's schema, with all the repitition that involves? I hope I'm wrong :-) -
Pro*C/C++ generates error "PCC-S-02015, unable to open include file"
I'm running a .pc file through the pre-compiler (on Windows 7x64 with instant client 12.1) and get the following error:
Error at line 78, column 1 in file XXX.pc
EXEC SQL INCLUDE SQLCA;
1
PCC-S-02015, unable to open include file
If I change the content of my file to the following
#include "sqlca.h"
//EXEC SQL INCLUDE SQLCA;
the pre-compiler does it's job nicely.
My pcscfg.cfg looks like this:
include="C:\PROGRA~2\Oracle\INSTAN~1\sdk\include"
include="C:\PROGRA~2\MICROS~2.0\VC\include"
define=(WIN32_LEAN_AND_MEAN)
DEFINE=_WSTDIO_DEFINED
Has there been a change in the syntax of Pro*C or why can't it resolve the EXEC SQL INCLUDE?
PS: I'm an absolute newbie to this and am trying to get to compile some veeery old code, build under instant client 9/10/11)Karl Esau (guest) wrote:
: Hi,
: I have problems to get the precompiler running - executing the
: precompiler leads to a segfault.
I meanwhile solved the problem, so that I can compile and
run the samples.
a strace on 'proc' showed:
open("/oracle/precomp/public/SQLCA.H", O_RDONLY) = -1 ENOENT
(Nosuch file or directory)
I made a symbolic link for an upper case SQLCA.H, needed to add
SQLCHECK=SEMANTICS in ~/precomp/admin/pcscfg.cfg and one more
lib for the make: /lib/libdl.so.2 because 'dlclose' and other
symbols were undefined.
bye
Karl Esau
null -
A few days ago my TV show and movie displays went whacky-the shows are no longer in alpha order, there are multiple listings of the same show, the pictures are random-including album covers. I downloaded latest version & no change. Any ideas??
ME TOO.
I think mine are all still in alphabetical order, but :
* movies I deleted from my library and told "hide this purchase in the cloud" are showing up again. If I try to play them, I get the "cannot find the file in its proper location, would you like to locate it" error message.
* for movies that have "iTunes Extras," the extras show up as a separate item, with another copy of the movie artwork. Most of these I believe I had DELETED the "iTunes Extras" anyway.
* Items are showing up multiple times.
* A few MUSIC ALBUMS are listed in my Movies section.
* Some movies (I believe ones that I deleted off my HD but are still in the cloud) are showing random album covers instead of their proper artwork.
* Just rented a movie, and it didn't show up anywhere in my library. It downloaded properly and completely, was in a suitably labeled folder in my iTunes/Media/Movies section, but didn't show up in any section of the library (or via a library search). Had to manually find it and tell it to open the file using iTunes.
Running the latest version, even checked for updates. No other changes made lately since the last round of apple software updates. This was wonky before the latest small update to iTunes - now it's even wonkier. And it is very, VERY effing annoying. -
Failure in Precompilation of JSPs due to include file in WL6.1 SP2
Hi
We are getting the following error when we try to do precompilation of JSPs using
precompile param to true in weblogic.xml
We are deploying our application as war files.
eagerly waiting for your help
sincerely
Ramesh
Issue description and StackTrace:
Issue:
Precompilation of JSPs fail while using precompile param to true in weblogic.xml and deploy it as War file. It is througing "failure pre-compiling JSP's
weblogic.utils.ParsingException: nested TokenStreamException: antlr.TokenStreamE
xception: Could not include index.jsp" exception.
OS: Windows 2000
Jdk: Sun Jdk1.3.1
Weblogic: 6.1 SP2
***Stacktrace*************
<Dec 17, 2002 1:05:51 PM CST> <Error> <HTTP> <[WebAppServletContext(3961036,AdvW
eb,/AdvWeb)] failure pre-compiling JSP's
weblogic.utils.ParsingException: nested TokenStreamException: antlr.TokenStreamE
xception: Could not include index.jsp
at weblogic.servlet.jsp.JspLexer.parse(JspLexer.java:1025)
at weblogic.servlet.jsp.JspParser.doit(JspParser.java:80)
at weblogic.servlet.jsp.JspParser.parse(JspParser.java:183)
at weblogic.servlet.jsp.Jsp2Java.outputs(Jsp2Java.java:119)
at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java:255
Ramesh,
We experienced this sympton as well. In our JSPs, we converted
<%@ include file="xyz.jsp"%> (static include, source time) to
<jsp:include page="licensedQuote.jsp"/> (dynamic include, run time)
and the problem went away.
We still use static includes at the very start of the JSPs. It seems the problem only occurs when the static include is inside of a tag whose body does JSP evaluation.
-Charlie
"Ramesh Danala" <[email protected]> wrote in message news:[email protected]...
> Hi
> We are getting the following error when we try to do precompilation of JSPs using
> precompile param to true in weblogic.xml
> We are deploying our application as war files.
> eagerly waiting for your help
> sincerely
> Ramesh
>
> Issue description and StackTrace:
> Issue:
>
> Precompilation of JSPs fail while using precompile param to true in weblogic.xml and deploy it as War file. It is througing "failure pre-compiling JSP's
> weblogic.utils.ParsingException: nested TokenStreamException: antlr.TokenStreamE
> xception: Could not include index.jsp" exception.
>
> OS: Windows 2000
> Jdk: Sun Jdk1.3.1
> Weblogic: 6.1 SP2
>
> ***Stacktrace*************
>
> <Dec 17, 2002 1:05:51 PM CST> <Error> <HTTP> <[WebAppServletContext(3961036,AdvW
> eb,/AdvWeb)] failure pre-compiling JSP's
> weblogic.utils.ParsingException: nested TokenStreamException: antlr.TokenStreamE
> xception: Could not include index.jsp
> at weblogic.servlet.jsp.JspLexer.parse(JspLexer.java:1025)
> at weblogic.servlet.jsp.JspParser.doit(JspParser.java:80)
> at weblogic.servlet.jsp.JspParser.parse(JspParser.java:183)
> at weblogic.servlet.jsp.Jsp2Java.outputs(Jsp2Java.java:119)
> at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java:255
> )
-
How to change the filename in @include file?
I want to do a checking before deciding to include which file,
for example,
<%
if(isValid){
%>
<%@ include file="abc.jsp" %>
<%
else{ %>
<%@ include file="def.jsp" %>
<% } %>but the code above doesnt work in my JSPs
any idea how to solve this?
thanks
DesmondAm i clear?? pls correct me if i am wrong..You are wrong.
The include directive is being used here, which is a compile time include, not a runtime include. Both includes will be performed before the resulting servlet is compiled.
If they have a conflict between them (either by not nesting them in their own { scope } or using <%! declarations %>) then the generated servlet will fail to compile.
So if you had the following:
abc.jsp:
Hello from ABC!
<% String myVar = "ABC"; %>def.jsp:
Hello from DEF!
<% String myVar = "DEF"; %>And the page as mentioned in the original post, you would end up with a Servlet something like this:
if (isValid){
out.println("Hello from ABC!");
String myVar = "ABC";
else{
out.println("Hello from DEF!");
String myVar = "DEF";
}This example would compile because of the presence of the braces.
However removing the braces or using a <%! declaration %> would probably screw things up with a compile error.
The %Include directive is like a copy/paste into a JSP before you compile it.
The <jsp:include> is evaluated at runtime and copies in the result of executing the page.
The difference is quite subtle, but very important.
Cheers,
evnafets -
How to generate a second csv file with different report columns selected?
Hi. Everybody:
How to generate a second csv file with different report columns selected?
The first csv file is easy (report attributes -> report export -> enable CSV output Yes). However, our users demand 2 csv files with different report columns selected to meet their different needs.
(The users don't want to have one csv file with all report columns included. They just want to get whatever they need directly, no extra columns)
Thank you for any help!
MZHello,
I'm doing it usually. Typically example would be in the report only the column "FIRST_NAME" and "LAST_NAME" displayed whereas
in the csv exported with the UTL_FILE the complete address (street, housenumber, additions, zip, town, state ... ) is written, these things are needed e.g. the form letters.
You do not need another page, just an additional button named e.g. "export_to_csv" on your report page.
The csv export itself is handled from a plsql procedure "stored procedure" ( I like to have business logic outside of apex) which is invoked by pressing the button "export_to_csv". Of course the stored procedure can handle also parameters
An example code would be something like
PROCEDURE srn_brief_mitglieder (
p_start_mg_nr IN NUMBER,
p_ende_mg_nr IN NUMBER
AS
export_file UTL_FILE.FILE_TYPE;
l_line VARCHAR2(20000);
l_lfd NUMBER;
l_dateiname VARCHAR2(100);
l_datum VARCHAR2(20);
l_hilfe VARCHAR2(20);
CURSOR c1 IS
SELECT
MG_NR
,TO_CHAR(MG_BEITRITT,'dd.mm.yyyy') AS MG_BEITRITT ,TO_CHAR(MG_AUFNAHME,'dd.mm.yyyy') AS MG_AUFNAHME
,MG_ANREDE ,MG_TITEL ,MG_NACHNAME ,MG_VORNAME
,MG_STRASSE ,MG_HNR ,MG_ZUSATZ ,MG_PLZ ,MG_ORT
FROM MITGLIEDER
WHERE MG_NR >= p_start_mg_nr
AND MG_NR <= p_ende_mg_nr
--WHERE ROWNUM < 10
ORDER BY MG_NR;
BEGIN
SELECT TO_CHAR(SYSDATE, 'yyyy_mm_dd' ) INTO l_datum FROM DUAL;
SELECT TO_CHAR(SYSDATE, 'hh24miss' ) INTO l_hilfe FROM DUAL;
l_datum := l_datum||'_'||l_hilfe;
--DBMS_OUTPUT.PUT_LINE ( l_datum);
l_dateiname := 'SRNBRIEF_MITGLIEDER_'||l_datum||'.CSV';
--DBMS_OUTPUT.PUT_LINE ( l_dateiname);
export_file := UTL_FILE.FOPEN('EXPORTDIR', l_dateiname, 'W');
l_line := '';
--HEADER
l_line := '"NR"|"BEITRITT"|"AUFNAHME"|"ANREDE"|"TITEL"|"NACHNAME"|"VORNAME"';
l_line := l_line||'|"STRASSE"|"HNR"|"ZUSATZ"|"PLZ"|"ORT"';
UTL_FILE.PUT_LINE(export_file, l_line);
FOR rec IN c1
LOOP
l_line := '"'||rec.MG_NR||'"';
l_line := l_line||'|"'||rec.MG_BEITRITT||'"|"' ||rec.MG_AUFNAHME||'"';
l_line := l_line||'|"'||rec.MG_ANREDE||'"|"'||rec.MG_TITEL||'"|"'||rec.MG_NACHNAME||'"|"'||rec.MG_VORNAME||'"';
l_line := l_line||'|"'||rec.MG_STRASSE||'"|"'||rec.MG_HNR||'"|"'||rec.MG_ZUSATZ||'"|"'||rec.MG_PLZ||'"|"'||rec.MG_ORT||'"';
-- DBMS_OUTPUT.PUT_LINE (l_line);
-- in datei schreiben
UTL_FILE.PUT_LINE(export_file, l_line);
END LOOP;
UTL_FILE.FCLOSE(export_file);
END srn_brief_mitglieder;Edited by: wucis on Nov 6, 2011 9:09 AM -
Development environment for 'include' files?
My photo album program only has a single page. Each time you
ask for a new page
it calls itself, with a new set of parameters. Some of the
more complicated
pages are generated by setting up a framework (which
specifies the styles to be
used, among other things) and then loading an include file
into it.
Initially I envisaged these as being simple text files, but
inevitably some of
them became quite complex. Developing these in Dreamweaver is
quite a pain,
because it doesn't know about the CSS styles. I did try
making an HTML shell
file and pasting the include file into it, then cutting and
pasting it again to
save the revised version, but this proved to be cumbersome
and very error-prone.
Is there any way of telling Dreamweaver to load an
environment before loading
the include file?
Clancy> This seems to be about 90% of what I was thinking of,
but I gather that
> when you
> upload the file the hidden stylesheet remains attached
to the file, but is
> effectively commented out.
No. It's only "applied" during Design-time viewing.
> It is a pity that Dreamweaver doesn't include a
'compile' option which
> stripped
> out template and other Dreamweaver specific commands
(end_editable and the
> like)
> from the development file, leaving clean HTML. If this
were done it
> would mean
> that they could use Dreamweaver specific operations much
more flexibly,
> without
> having to worry about using botched up comment commands
to hide them from
> the
> browser.
I guess I don't understand what you are referring to here
with "botched up
comment commands". A comment is a comment, and really does
nothing to the
page at all.
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.dreamweavermx-templates.com
- Template Triage!
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
http://www.macromedia.com/support/search/
- Macromedia (MM) Technotes
==================
"Clancy" <[email protected]> wrote in message
news:[email protected]...
> "Murray *ACE*" <[email protected]>
wrote:
>
>>Use Design-time stylesheets.
>
> Thanks Murray,
>
> This seems to be about 90% of what I was thinking of,
but I gather that
> when you
> upload the file the hidden stylesheet remains attached
to the file, but is
> effectively commented out. However I guess that all that
has to be in the
> file
> is an 'include' statement (or perhaps this is what
actually happens), so
> it
> shouldn't lengthen the file noticeably.
>
> It is a pity that Dreamweaver doesn't include a
'compile' option which
> stripped
> out template and other Dreamweaver specific commands
(end_editable and the
> like)
> from the development file, leaving clean HTML. If this
were done it
> would mean
> that they could use Dreamweaver specific operations much
more flexibly,
> without
> having to worry about using botched up comment commands
to hide them from
> the
> browser.
>
> Clancy -
In Flash CS4 a generated html with swf file won't play swf
Using Flash CS4 and having the Flash plug-in ver 10 on my PC, the generated html file will not play the swf in the browser.
I noticed that the active-x javascript is now included in the header as well as the javascript portion in the body tag.
But it won't play. I get the typical blank window in IE with the "X" in the upper left corner.
I don't have this problem with Flash CS3.
Any ideas what may be going on?
Thank you.I am having similar difficulty; mostly I am confused.
I want to open a flash video file in a frame within a webpage.
I have generated a Flash CS4 html and swf file. When loaded they play, but they play on a separate, full size web page, not in the frame where I want it.
I then generated FLV and F4V files but that doesn't work.
It appears that I need to insert the object and embed tags "for Flash Movies" in the html file.
Once I do that, do I go back to only putting in the html and swf files and create a link to the html file to bring up the video in the target frame?
What are the FLV files for? -
I need to use dynamically generated file names in my <%@ include file="" %> directive.
I am using objects (such as database connection) in the files included which I created in my base JSP file. For this reason, I cannot use the jsp:include tag (since these objects are not defined in these files, the servlet doesn't compile).
Are there any ways of using these dynamic names in this directive?If you are dymically generating the file, then store it in a string and then include it?
String dynamicallyGeneratedFileName = (however you are generating the file name);
<%@ include file="<%=dynamicallyGeneratedFileName%>" %> -
I have bought a power supply with an RS232 computer interface. The
software consists in a .dll and a .lib files (32-bit, written in C or
C++). I don't know how to write the include file to link my LabWindows/CVI
project to the libraries...
In the .dll I've functions defined like: int configcom (int Comport)
I hope you can help me!
Caterina DucatiThat is very strange. A header file should always be provided with a DLL in order to program with it. Sometimes an import library (.lib) is not provided and CVI can generate on of those for you from the header file, but it can't generate a header file from a DLL or LIB. You really should contact the company that provided you the power supply and get a header file from them.
You can find out the function names in the DLL, but I know of no way to rebuild the header since you will not have the argument lists.
Best Regards,
Chris Matthews
National Instruments -
Including files/resources using the ADT command line
Hi all,
I'm trying to get file support into my ADT helper tool before I release an update. I am still having problems.
According to the Adobe docs on the subject, the following commands can be used:
-C "path/to/new/working/directory" [files and folders to include]
-e [files and folders to include] [package directory to add these to]
The following example works fine for me:
// This changes the working directory to my audio resources folder, and then packages the file 'track.mp3' into the root folder of my application package.
-C "C:\\resources\audio" "track.mp3"
Hoiwever using -e option in any way generates an error:
// This copies the file 'sfx.mp3' from the current working directory to the application package subdirectory 'lib'
-e sfx.mp3 lib
This also causes an error:
// Change the working directory to resources/audio and then copy the file called 'sfx.mp3' to the 'lib' subfolder of the application package. Error.
-C "C:\\resources\audio" -e sfx.mp3 lib
The error in both cases is:
File does not exist: sfx.mp3
Any ideas how I can use the -e option? Does the working directory not come in to it - do i always have to use an absolute path to my file?
Thanks in advance,
PeterNot sure if it will help in your situation, but I just include files by adding the filepath at the end of my adt command line (no -e or -c). Eg (included files or bolded):
"C:\Program Files (x86)\Java\jre6\bin\java" -jar C:\Users\t.randall\Documents\AIRSDK\AIR_3.0\lib\adt.jar -package -target ipa-ad-hoc -storetype pkcs12 -keystore ..\..\Deployment\CareerBox.p12 -storepass pass -provisioning-profile ..\..\Deployment\CareerBox.mobileprovision ..\..\CareerBox.ipa CareerBox_iPhone-app.xml CareerBox_iPhone.swf AppIconsForPublish\Icon29x.png AppIconsForPublish\Icon57x.png AppIconsForPublish\[email protected] AppIconsForPublish\Icon512x.png AppIconsForPublish\Icon48x.png AppIconsForPublish\Icon72x.png Default.png [email protected] Default-Landscape~ipad.png Data\Cards.xml Data\CareerCards.xml -
Newbie to VC++
Getting the below error in VC++ 2005, Indesign CS4
1>------ Build started: Project: WriteFishPrice, Configuration: Debug Win32 ------
1>Performing Custom Build Step
1>Compiling...
1>WFPNoStrip.cpp
1>C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp(19) : fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
1>WFPID.cpp
1>C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp(19) : fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
1>VCPlugInHeaders.cpp
1>C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp(19) : fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
1>TriggerResourceDeps.cpp
1>C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp(19) : fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
1>SDKPlugInEntrypoint.cpp
1>C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp(19) : fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
1>Generating Code...
1>Build log was saved at "file://c:\id6sdk\build\win\objD\WriteFishPrice\BuildLog.htm"
1>WriteFishPrice - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have added the path of config.hpp in "addition include directories" still it is throwing the same error.
Regards,
SureshNeither the first not the second one:
am using the following path:
C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\external\asl\boost_libraries\boost
Now i have copied the complete 'external' folder to C:\id6sdk\ and added the directory now it is showing the following error:
Getting the following error:
fatal error C1083: Cannot open include file: 'IPMUnknown.h': No such file or directory C:\Program Files\Adobe\adobe_indesign_cs4_products_sdk_578win\source\precomp\common\ShukHeaders.cp 46
Don't understand the concept one error leading to the other error.
How to come out of these kind of problem.
Regards,
Suresh -
Using WL5.1, JSPC can't seem to find files included in a JSP, such as:
<%@ include file="include/include_file.inc" %>
The docroot is set to the directory containing the JSP files, and the
include directory (which contains all included files) is directly under the
docroot directory.
In the generated java file we get:
// cannot include file 'include/include_file.inc' //[ /BrandEdit.jsp; Line:
33]
//[ /BrandEdit.jsp; Line: 34]
out.println("<!-- cannot include file 'include/include_file.inc', resource
not found -->"); //[ /BrandEdit.jsp; Line: 33]
//[ /BrandEdit.jsp; Line: 34]
Any ideas on why the included files aren't being found by JSPC?
Thanks,
Steve
Fixed in SP9 - available very soon.
ISSUE 38661
Compiling a JSP that contains an include directive with a relative URI was
not resulting in the file's path being parsed correctly.
Mike
"Steve Crook" <[email protected]> wrote in message
news:3ac97e4d$[email protected]..
> Using WL5.1, JSPC can't seem to find files included in a JSP, such as:
> <%@ include file="include/include_file.inc" %>
>
> The docroot is set to the directory containing the JSP files, and the
> include directory (which contains all included files) is directly under
the
> docroot directory.
>
> In the generated java file we get:
> // cannot include file 'include/include_file.inc'
ile://[ /BrandEdit.jsp; Line:
> 33]
> file://[ /BrandEdit.jsp; Line: 34]
> out.println("<!-- cannot include file 'include/include_file.inc', resource
> not found -->"); file://[ /BrandEdit.jsp; Line: 33]
> file://[ /BrandEdit.jsp; Line: 34]
>
> Any ideas on why the included files aren't being found by JSPC?
>
> Thanks,
> Steve
>
>
-
Random Access File not working, Need Help!!!!
I am having trouble creating and displaying a Random Access File for hardware tools. I have included the code below in eight files:
// 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 = 72;
// 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: WriteRandomFile.java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class WriteRandomFile
private RandomAccessFile output;
private static final int NUMBER_RECORDS = 100;
// enable user to choose file to open
public void openFile()
try // open file
output = new RandomAccessFile("hardware.dat","rw");
} // end try
catch (IOException ioException)
System.err.println("File does not exist.");
} // end catch
} // end method openFile
// close file and terminate application
public void closeFile()
try // close file and exit
if (output != null)
output.close();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
// add records to file
public void addRecords()
// object to be written to file
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
int recordNumber = 0;
String toolName;
int quantity;
double cost;
Scanner input = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator ",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s %s\n%s", "Enter record number (1-100),",
"tool name, quantity and cost.","? ");
while (input.hasNext())
try // output values to file
recordNumber = input.nextInt(); // read record number
toolName = input.next(); // read tool name
quantity = input.nextInt(); // read quantity
cost = input.nextDouble(); // read cost
if (recordNumber > 0 && recordNumber <= NUMBER_RECORDS)
record.setRecordNumber(recordNumber);
record.setToolName(toolName);
record.setQuantity(quantity);
record.setCost(cost);
output.seek((recordNumber - 1) * // position to proper
RandomAccessHardwareRecord.SIZE); // location for file
record.write(output);
} // end if
else
System.out.println("Account must be between 0 and 100.");
} // end try
catch (IOException ioException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so enter can try again
} // end catch
System.out.printf("%s %s\n%s","Enter record number (1-100),",
"tool name, quantity and cost.", "? ");
} // end while
} // end method addRecords
} // end class WriteRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: WriteRandomFileTest.java
// Testing class WriteRandomFile
public class WriteRandomFileTest
// main method begins program execution
public static void main( String args[] )
WriteRandomFile application = new WriteRandomFile();
application.openFile();
application.addRecords();
application.closeFile();
} // end main
} // end class WriteRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: ReadRandomFile.java
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class ReadRandomFile
private RandomAccessFile input;
// enable user to select file to open
public void openFile()
try // open file
input = new RandomAccessFile("hardware.dat","r");
} // end try
catch (IOException ioException)
System.err.println("File does not exist.");
} // end catch
} // end method openFile
// 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
while(true)
do
record.read(input);
}while (record.getRecordNumber() == 0);
// display record contents
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end while
} // end try
catch (EOFException eofException)
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
// close file and terminate application
public void closeFile()
try // close file and exit
if (input != null)
input.close();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end methode closeFile
} // end class ReadRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: ReadRandomFileTest.java
// Testing class ReadRandomFile
public class ReadRandomFileTest
// main method begins program execution
public static void main( String args[] )
ReadRandomFile application = new ReadRandomFile();
application.openFile();
application.readRecords();
application.closeFile();
} // end main
} // end class ReadRandomFileTest-------------------------------------------------------------------------------------------------
Below is the sample data to be inputted in the random file:
Record Tool Name Quantity Cost
Number
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.48I have managed to fix your program.
The solution
The records are sized by the various Writes that occur.
A record is an int + 15 chars + int + double.
WriteInt writes 4 bytes
WriteChar (Called by WriteChars) write 2 bytes
WriteDouble writes 8 bytes.
(In Java 1.5 )
4 bytes + 30 Bytes + 4Bytes + 8 Bytes. = 46 Bytes.
The details are in the API for Random Acces Files at
http://java.sun.com/j2se/1.5.0/docs/api/java/io/RandomAccessFile.html
The code for RandomAccessHardwareRecord line
public statis final int SIZE = 72needs to have the 72 changed to 46
This should make your code work.
I have hacked around with some other bits and will send you my code if you want but that is the key. The asnwers you were getting illustrated a bunch of bytes being read as (say) an int and beacuse of the wrong record length, they were just a bunch of 4 bytes that evaluated to whetever was at that point in the file.
When the record was written the line
output.seek((recordNumber -1 ) * RandomAccessHardwareRecord.SIZE);had SIZE as 72 and so the seek operation stuck the file pointer in the wrong place.
This kind of stuff is good fun and good learning for mentally getting a feel for record filing but in real problems you either serialize your objects or use XML (better) or use jdbc (possibley even better depending on what you are doing).
I would echo sabre comment about the program being poor though because
If the program is meant to teach, it is littered with overly complex statements and if it is meant to be a meaningful program, the objects are too tied to hardware and DAO is the way to go. The problem that the program has indicates that maybe it is maybe fairly old and not written with java 2 in mind.
As for toString() and "Yuk"
Every class inherits toString() from Object. so if you System.out.println(Any object) then you will get something printed. What gets printed is determined by a complex hieracrchy of classes unless you overRide it with your own method.
If you use UnitTesting (which would prevent incorrect code getting as far as this code did in having an error), then toString() methods are really very useful.
Furthermore, IMO Since RandomAccessHardwareRecord knows how to file itself then I hardly think that knowing how to print itself to the console is a capital offence.
In order to expand on the 72 / 46 byte problem.
Message was edited by:
nerak99
Maybe you are looking for
-
My iPhone 4 started playing up a few days ago. First it deleted 250 photos ( of my sons birth) then next day it deleted another 50. Now it won't let me take any photos receive any photo msg's and save photos. Aswell it has started to get out of msg a
-
hi, can anyone help me to get the data for a file in dms with a specific doknr? i need to get the binary data to send them per mail. I searched in function group cv120 (i tried cv120_read_file2table but it doesn't work for me) but wasn't able find a
-
Problem in printing main window
Hi all i have to print first four coloums with multiple records and fifth coloumn with data shown below ,how can i print this i have to display like this(ABCDE are my five coloumns)under coloumn E , i have to display text and values like shown,and f
-
How to change the name of External Hard Disk?
I am new to Mac so if this is really easy and I am being completely lame here please excuse me. I have an External Hard Drive that is being used by Time Machine. I don't want to see it on the desktop so I was going to change the name so it had a '.'
-
Hot corners do not work. Is there a plist that can be deleted to rectify this?
Is there a plist that can be deleted for hot corners? I cannot get them to work at all. Thanks for any help.