(4) Java - FAQ

来源:互联网 发布:gson解析json数组list 编辑:程序博客网 时间:2024/04/25 06:14
Applet/IE Version App. First EXE Jar JWS Classpath Path Portability Java!=JS
General First Steps Search Homework Multi/X-post Top-Post Specific Example Code Error Message StackTrace
Resources News Groups Mailing Lists Related FAQ's Contributors

Java - FAQ

Questions & Answers

Applets

My applet works fine on my PC, but my friend who uses IE says he gets a class not found or applet not inited message.

Internet Explorer and, as time goes by, other browsers, will not include the Java Plug-In by default. The obtuse messages "class not found", and "applet not inited" are MicroSoft's way of telling you that this is a version of their operating system component that either includes no JVM, or the very broken and insecure MS VM, which is arguably worse.

If the user has already installed the Java plug-in and is still getting the message, it is probably that you need to configure IE to use the Java plug-in instead of the MS VM. To achieve this, go to IE options (Alt t, then o), select the 'Advanced' tab, and ensure the entry marked Java (Sun) - Use Java 2 is selected.

My app. runs on 1.n VM's, but breaks on earliers ones. How do I ensure the user has a minimum Java version?

Sun provides the HTMLconverter to change HTML applet tags to use the object or embed tags instead. This solution works well until you specify support for 'all browsers', whereupon the HTMLConverter produces browser sniffing JavaScript in an attempt to determine the correct tag to use.

A superior way to ensure a Java minimum version is to use the 100% Java solution - JavaVersionApplet, which will check the browser's VM on any web page and redirect to another page if the minimum version is not installed.

What are unsigned applets prevented from doing?

The JRE runs untrusted (or unsigned) applets in a strict security sandbox to ensure they do not damage the user's computer. Included amongst the things applets cannot do are read files, open network connections to hosts other than the one from which it originated and a slew of other actions that may in any way compromise the user's system integrity, or privacy.

Check the Sun Applet Security FAQ for more details, or this comprehensive list of Applet restrictions at the Java Glossary.

Somebody tells me I should develop my applet as an application first, but I do not want an application, so why does that make sense?

Oscar Kind notes..

Because it's easier.

Learning is best done one step at a time. This is possible using a command line application, as the basics (a "Hello world" program) can be as small as 5 lines. You only need to implement your idea.

If you try implementing your idea as a GUI application, this adds several concepts:

  • GUI components and how they build an interface
  • The event model

If you try developing your idea as an applet, this adds the applet lifecycle (which is far from trivial) to the additions of a GUI application.

As you can see, these are all extra concepts. They make it more difficult to produce something workable: each extra concept is approximately twice as hard to master than when it's tackled individually.

By starting with a command line program, you can focus on your idea. Once you have that done, you can add a GUI. When the GUI is done, you can make the application into an applet.

Note that in each step, the complexity is reduced: the whole process is easier than when you start with an applet.

Andrew Thompson adds, but wait Oscar, it doesn't stop there!

The testing and development cycle of applets is so much higher than that of GUI'd applications that it is often faster to add a frame to an applet purely to speed development.

For example. To test changes to an 'all privileges' application you need to

  1. Compile it.
  2. Run it.

To do the same for an applet you need to.

  1. Compile it
  2. Jar it
  3. Sign the jar
  4. Flush the Java cache in the browser
  5. Refresh the web page

Three more steps are needed to test any change to the code, and I wish I had a dollar for every time a problem was caused because the developer forgot point 4.

Another thing that slows applet development is that problems can arise from interaction with

  • Other applets or Javascript,
  • The HTML and styles of the web page itself
  • The browser and the
  • VM that the browser is configured to use, or completely lacks.

Browsers or browser plug-ins can cause problems with new windows, changing pages, the messages to the status bar, tiny applets, signed applets and more.

Writing applets has been known to drive people mad, Mad, MAD!!! Ahem.. (clears throat).

Applet development is not for the faint hearted. You should have a clear understanding of the basic Java concepts, GUI's and debugging before you attempt to write applets.

.EXE

How do I make a Windows .exe file from my Java .class files?

There are a number of good reasons not to package your application in an executable. Daniel Sjöblom notes:

Jon A. Cruz details some of the extra steps in the development process required to create an exe. He points out that developers making native exe's need to:

  • Validate the latest versions of the compilation product from the vendor. If critical bugs are found, it can't be used to build a shipping product until those are addressed. Work that needs to be done each time a revision comes out from the vendor.
  • Submit the software through a QA cycle. Once engineering thinks things are done, they need to be verified. So every shipping version and update of a product needs to go through complete testing cycles.
  • Further, since native compilation is per target platform, the QA cycle needs to be done completely for each target platform, which multiplies effort required.
  • Shelf space. Maybe not a big deal nowadays, but could be.
  • Then one needs to get all customers to upgrade to the proper version. Either have free updates (in which case the business needs to absorb the cost of producing updates) or alternatively needs to handle clients not all updating.

Jon notes futher: When you ship standard Java bytecodes, VM problems are the responsibility of the platform or VM vendor. However, when you ship compiled binaries, they become your responsibility (even if they're actually bugs in the vendor's compilation product).

The best solution is to deliver your application or applet via Java Web Start, but if have determined that a native exe does suit the needs of the customer, you can consult the mindprod page devoted to native compilers.

Further reading on the subject can be found through the newsgroups, searching for "make exe" & "create exe".

Jar packaging /signing

How do I make my Java 'double click - launch' like .exe's?

Java classes can be packaged into jar files (a specialized form of zip file) using the Jar tool. To make a jar that is 'double-click launchable', you also need to add a manifest.mf file that specifies the main class.

More information can be found by googling the groups for make jar or create jar.

A Jar file can be installed to a users machine using Java WebStart.

Java Webstart

What is the best way to distribute my application?

Java Webstart is the best way to deliver your application or applet to your users, directly off the internet or CD. It supports advanced options as well as auto-update and access to secure resources.

JWS applications and applets that are not signed operate within a strict security sandbox, similar to the browser based security sandbox used for unsigned applets.

Classpath

Why am I getting a NoClassDefFound error?

This error occurs because the Java Virtual Machine is unable to locate the class in the existing classpath. You need to include the jar archive or directory containing the class to the classpath. For more information see Sun's FAQ. You can also find more information on the Java forums searching for NoClassDefFoundError.

How do I set the classpath?

Sun's documents on setting the Windows or Linux/Solaris should set you on the right track. For further advice you might search the groups using keyword classpath.

I/O

How do I find the path to the application directory?

This is usually a 'wrong question', as it indicates a flaw in the design of your program, your thinking, or both.

A programmer can use the method Class.getResource("Anything.txt") to get an URL pointing to anything on the current classpath. This includes files, directories, files in directories, files in directories of zip and jar archives..

The other case where this regularly pops up is when a programmer wishes to save some program properties (e.g. GUI size and location) in the directory in which the program resides. The best way to store program properties is invoke the Properties.getProperty("user.home") method to get the location of the user's home directory, then write a single String in the user's home directory that stores the path to the main application properties. This has the added advantage that the user can then decide where they want to store them.

Portability

My application works fine on Windows (Mac/Unix/Linux) but breaks when running on (another OS), I though Java was supposed to be cross-platform, why doesn't it work?

System properties Write Once, Run Anywhere: Why it Matters, The Java Glossary on portability.

Further information is available on the Java forums about System reliant EOL, System reliant path separator

Java!=JavaScript

I am asking how to write java script, why are people telling me I have the wrong group?

Java and JavaScript are different languages. Java Vs. JavaScript explains the differences between them. Once you have worked out which one you need, try comp.lang.javascript, or, comp.lang.java.*

General

First Steps

The comp.lang.java.help usenet newsgroup the best place to go for help in fixing problems with the basic set-up and configuration of the Java development environment. Other good resources for beginners can be found in the Java Glossary on getting started as well as Patricia Shanahan's help for beginners and Jon Skeet's random clutch of java resources.

Search google

Most problems have been encountered and solved before. The answers are documented in the archives of the usenet newsgroups.

If you fail to find answers by searching, mention that in any post asking for help, but consult the smart questions checklist to ensure you have done the correct preparation before posting.

Homework

The people who help on newsgroups generally do so for the nice feeling they get when they have helped to explain an aspect of their chosen craft/talent to someone who is learning. If a person arrives at the group seeking such knowledge, they will find plenty of help through the forum.

On the other hand, we won't do your homework for you! If you ask for the codes to a problem, it indicates that you are more interested in passing a course than actually learning. Any attempt to get your homework done by others will generally result in public and merciless ridicule.

Multi/cross-posting

Sometimes it is not clear which group a question belongs in, so the poster sends it to two (or more) separate groups. This is known as multi-posting and is very counterproductive, as it causes different threads to develop on those different groups. There are other good reasons not to multi-post, but instead to restrict your post to a single group, or alternately cross-post it (check the link above).

Having said that, don't cross-post either. Only people who already understand the scope and nature of the groups should consider cross-posting, and even then should only do so on rare occasions. In a nutshell, if you have any doubt that a message should be cross-posted, don't!.

Netiquette

A) Top-posting!

Q) What is the most irritating thing on usenet?

Top-posting refers to the practice of inserting a response above earlier responses. This destroys the thread of a conversation and makes it difficult to follow.

Many arguments have ensued in relation to this practise. The few that practise it put forward a number of unconvincing arguments in it's defence. The single most silly argument is that when you go to reply to a post, the newsreader software often places the cursor at the top of the previous post. Computer keyboards have a down key, please use it.

To understand more about why top-posting is discouraged, check this artice on top-posting.

Bottom posting is a better way to respond, but it also has it's pitfalls. Some folks mistakenly think that by putting their response at the very bottom of an earlier post, they are posting correctly and to everyone's best advantage. Wrong.

To qoute 140 lines of earlier messages in order to add 'I agree' at the very bottom is a waste of the bandwidth of every member of the group, as well as an added burden on the servers that host newsgroups, and the traffic between them.

The best way to reply is known as posting 'in-line with trimming'. This means putting your comments directly after the part you are commenting on, and deleting everything else.

Be specific

Ensure you understand what you are asking for. A vague question will be less likely to get an answer. Use this handy checklist to ensure you ask a smart question.

Post compilable code.

Post a short, self contained, compilable example, an SSCCE makes it much easier for others to help you, as they can observe the exact problem themselves.

Exact error message

A code example is not always necessary in order to solve a problem. Sometimes problems can be fixed just by understanding the error message you get. If you post error messages, or exception stack traces, be sure to post the exact message you are receiving.

A typical exception stack trace is shown below.

 Command Prompt
C:/>java -classpath . URLEncoderTest http://www.physci.org/kbd.jsp?key=del'http://www.physci.org/kbd.jsp?key=del' encoded succesfully.C:/>java -classpath . URLEncoderTest http://www.physci.org/java.lang.NullPointerException  at URLEncoderTest.getParameters(URLEncoderTest.java:32)  at URLEncoderTest.(URLEncoderTest.java:20)  at URLEncoderTest.main(URLEncoderTest.java:82)...

This message tells us three important things.

  • What went wrong? A NullPointerException happened.
  • In which Java source file did it first become apparent? URLEncoderTest.
  • What is the exact line number that the error became apparent? Line 32

..Could it actually get easier?!?

Now look at line 32 of the URLEncoderTest source code (below). Here we we can see the likely culprit, 's', which gets the value of the URL query string from the previous line.

This code was expecting a query string but none was supplied.

 29 ... 30    public String[][] getParameters( URL url ) { 31        String s = url.getQuery(); 32        String[] parms = s.split("&"); 33        String[][] allPrm = new String[ parms.length ][]; 34        for (int ii=0; ii<allPrm.length; ii++) { 35            println( parms[ii] ); 36            allPrm[ii] = parms[ii].split("="); 37        } 38        return allPrm; 39    } 40 ...

The Java exceptions and error messages can sound like a foreign language at first. Fortunately the Java Glossary has a comprehensive list of error messages explained from the developers' perspective.

Roedy has made links specially for my visitors, direct to the compile time and run time error messages indexes, The main document is available at error messages: Java Glossary.

Another great resource for debugging can be found at the Debug Strategy tutorial by Patricia Shanahan. In this tutorial, she demonstrates how to debug a problem, step by step from start to end. The tutorial takes you from the detection of the bug, through to it's resolution.

Try/Catch - the StackTrace

Never 'swallow' exceptions in your code, especially if those exceptions "could not occur" (famous last words!). The following code is bad practice!

119 ...120        catch (FileNotFoundException e) {}121 ...

This is most important for code that breaks. If the code breaks, you need it to break noisily.

The Java virtual machines can give detailed information about the cause of an exception, and the series of code lines that led to the exception manifesting. This information is contained on the exception stack trace.

119 ...120        catch (FileNotFoundException e) {121            // this file is part of the jar!122            e.printStackTrace();123        }124 ...

Alternatively, if the exception can safely be ignored, document why.

119 ...120        catch (InterruptedException e) {121            // something interrupted the122            // sleep(), resume processing..123        }124 ...

Resources

  • Sun Microsystems - information from the makers of Java themselves.
    • The Java 2 Platform API Spec., more commonly referred to as the JavaDocs can be accessed by the main frames based document, though I would recommend you use the non-frames version if you have a slow connection. There is a also a handy utility to give the link to any class in the 1.4/1.5 JavaDocs, as well as the package JavaDocs and the source code itself, in this easy 'front-end' to the Java API.
    • Tech tips.
    • Sun on Applets
  • Real's How To lots of code examples. Real regular pops in to the Java groups..
  • JGuru - tips, articles, downloads..
  • PhySci.codes general code resources as well as the Tame Swing examples.
  • Java World is a source of industry news related to Java.

News Groups

The UseNet Newsgroups are forums for public discussion of topics by interested individuals. It costs no money to read, subscribe to or post to the newsgroups, but certain standards of behaviour are expected from contributors to these online communities.

The standards might best be summed up in 'Netiquette Guidelines' RFC 1855 and particularly sections 3.1.1 - General Guidelines for mailing lists and NetNews and 3.1.3 - NetNews Guidelines pertaining to newsgroups (under 'One-to-Many Communications'). Note that the suggestions in this document are neither standards nor rules, they are simple common sense.

The comp.lang.java.* forums for discussion of the Java programming language by Sun MicroSystems are unmoderated (excepting c.l.j.announce).

  • comp.lang.java.help. Set-up problems, catch-all first aid. The help group is the best one for programmers just starting in Java. Regular posters who deliver short sharp rebukes on c.l.j.programmer, have been known to give polite and detailed answers to the same questions on c.l.j.help. However, use of the c.l.j.help group is no excuse to skimp on your research.
  • comp.lang.java.programmer. Programming in the Java language. A forum for general questions related to the core Java language. J2EE (Enterprise Edition) discussions can also be found on c.l.j.p.. Questions of an advanced technical nature are welcome and expected on this group. Short sharp rebukes will be in store for any who dare post a lazy, ill-thought out, badly researched or otherwise stupid question to c.l.j.programmer.
  • comp.lang.java.gui. GUI toolkits and windowing: AWT, IFC etc. - Questions about the graphical user interface (Applets, Frames, Windows, Layouts..) should be directed here, but not before checking the GUI FAQ.
  • comp.lang.java.3d. 3D Graphics API's for the Java language.
  • comp.lang.java.advocacy. Support for and criticism of the Java System.
  • comp.lang.java.announce. Announcements re the Java System. (Moderated)
  • comp.lang.java.beans. Java software components (JavaBeans).
  • comp.lang.java.corba. Topics relating to Java and CORBA.
  • comp.lang.java.databases. Databases, java.sql, JDBC, ODBC.
  • comp.lang.java.machine. JVM, native methods, hardware.
  • comp.lang.java.security. Security issues raised by Java.
  • comp.lang.java.softwaretools. IDEs, browsers, compilers, other tools.

Related FAQ's

Interest Groups - Other

  • Multi-Media in Java is assisted by the Java Media Framework, the JMF has a forum available though the Sun site. To answer the single most common question asked of the JMF - 'Does JMF support MP3's?'. The answer is 'no', there is a Windows Performamce Pack that will play MP3's, but the cross-platform version does not.
  • Sun's Java Advanced Image API can be used for image operations that require more than is available in the standard API's. The JAI API is the subject of discussion in this Sun sponsored mailing list.
  • Check here for more Sun forums and user groups.

Contributors

The Java FAQ is written and maintained by Andrew Thompson, with help from the contributions of; Daniel Sjöblom, Darryl L. Pierce, Dave Glasser, Jon A. Cruz, Thomas Weidenfeller, Doug Pardee & Oscar Kind.

The contributors to this document provided a great deal of valuable information, but responsibility for the final document lies entirely with the author. If you find something good and right in this document, thank the contributors; for errors, omissions, typo's and opinions, blame the author



From:http://www.physci.org/codes/javafaq.jsp#exe
原创粉丝点击