简体   繁体   中英

System.getProperty(“user.dir”) with Eclipse IDE

I've been blasting through the Java Swing tutorials on zetcode.com

I've made it all the way to Basic Swing Components II, the JTextPane component. In this example, an HTML document is loaded into memory and placed into the textpane. In order to find the file, zetcode.com uses:

String cd = System.getProperty("user.dir") + "/";
textPane.setPage("File:///" + cd + "test.html");

My IDE of choice is Eclipse Kepler .

I have written the code for this example's class and created the HTML document exactly as zetcode.com has shown on the page. I have placed the HTML file in the same source folder and package as the class which uses it. But when I run the code, I hear a Windows system error sound and the JFrame pops up without any text inside the textpane.

EDIT 01: I've named the package "com/zetcode/swingtutorial/basiccomponents/". I've tried using getClass.getResource("/com/zetcode/swingtutorial/basiccomponents/test.html") and I figure I must have typed this correctly because I do not get an IOException.

EDIT 02: Here's another interesting thing: In zetcode's system, they've used "File:///", which caused Windows to play an error sound. But when I tried "File://", no error sound plays. D'you think that was just a typo on their part? Either way, my html doc still isn't displayed on the pane. :S

Do you know what I could be doing wrong?

Many thanks for your help!

Try this:

textPane.setPage(YourClass.class.getResource("test.html"));

If its in package

textPane.setPage(YourClass.class.getResource("/packagename/test.html"));

System.getProperty("user.dir");

Gives you the root context location or the project location folder or you can say the current directory when JVM was started Accordingly give the path or alternately Try loading this way

String pathOfHtmlFile = Thread.currentThread().getContextClassLoader()
                              .getResource("yourHtmlFile").getPath();
textPane.setPage(pathOfHtmlFile);

provided the file is in the classpath.

System.getProperty("user.dir")

Returns the "working folder" from which the application was launched. In Eclipse I believe the working directory is the top level project folder (not in src) or it's in the folder that contains the compiled .class files. Try copying the file to those folders and see when it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM