• Advertisement
Sign in to follow this  

[java] Working with Files

This topic is 3844 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ok, java claims that it can run on anything that has a screen (phones, calculators, tv's, wristwatches etc) but I tried to run my game on several computers and every time it gave me bad version exceptions. The computers have the same JRE and JVM (Windows). So what i gotta do is to get JDK, compile every java file, then it works fine. Is that how it works or am i missing something?
Java Plug-in 1.5.0_06
Using JRE version 1.5.0_06 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\Computer


----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------

java.lang.UnsupportedClassVersionError: Bad version number in .class file
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at sun.applet.AppletClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadCode(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
java.lang.UnsupportedClassVersionError: Bad version number in .class file
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at sun.applet.AppletClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadCode(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-9" java.lang.NullPointerException
	at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
	at sun.plugin.AppletViewer.showAppletException(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
	at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
	at sun.plugin.AppletViewer.showAppletStatus(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Exception in thread "thread applet-tennis1.class" java.lang.NullPointerException
	at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
	at sun.plugin.AppletViewer.showAppletException(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
java.lang.UnsupportedClassVersionError: Bad version number in .class file
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at sun.applet.AppletClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadCode(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-13" java.lang.NullPointerException
	at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
	at sun.plugin.AppletViewer.showAppletException(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
	at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
	at sun.plugin.AppletViewer.showAppletStatus(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
java.lang.UnsupportedClassVersionError: Bad version number in .class file
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at sun.applet.AppletClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.applet.AppletClassLoader.loadCode(Unknown Source)
	at sun.applet.AppletPanel.createApplet(Unknown Source)
	at sun.plugin.AppletViewer.createApplet(Unknown Source)
	at sun.applet.AppletPanel.runLoader(Unknown Source)
	at sun.applet.AppletPanel.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

[Edited by - alexxzius on July 24, 2007 3:35:15 PM]

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by alexxzius
The computers have the same JRE and JVM (Windows).


Are you sure? That error indicates that you are compiling with a newer JVM than what is on the machine that is trying to run your program. Are you using JDK v1.6 to compile with?

Share this post


Link to post
Share on other sites
if you are sure that they're all using 1.5, maybe you're compiling on 1.5.0_09 while they are running 1.5.0_06

Share this post


Link to post
Share on other sites
Java apps only throw bad version exceptions if the requisite version of Java is not installed. Go to java.sun.com and download the latest JRE.

I've been getting that error a lot because a new version of Java was released recently, and people have versions that are 1, sometimes 2, editions old.

Share this post


Link to post
Share on other sites
nevermind . . . It was just me saying things cause java is so difficult.

An unrelated qiuestion:
Can i draw stuff on an empty image and then draw that image on the screen? (please show code cause im stupid). ;0

Share this post


Link to post
Share on other sites
Quote:
Original post by alexxzius
nevermind . . . It was just me saying things cause java is so difficult.

An unrelated qiuestion:
Can i draw stuff on an empty image and then draw that image on the screen? (please show code cause im stupid). ;0



paint(Graphics g)
{
Image bg = new Image();
Graphics gI = bg.getGraphics()

//Draw stuff to bg image
gI.draw(...);

//draw bg to screen
g.drawImage(bg,...);
}


Share this post


Link to post
Share on other sites
it said here
Image bg = new Image();
Image is static and cant be instantiated . . .

EDIT:
ok, instead of
Image bg = new Image();

i put
Image bg=createImage(room_width,room_height);

It is working now but not with the desired results. What i wanted to do is to cut down on my CPU. Originally i had a double for loop that drew 192 tiles (16 x 12) to Graphics g every step (30 times a second). My idea was to draw the tiles on an image and then draw it on the screen (which happens on average every 5 seconds). But my CPU went higher when doing it. Is it normal or am i doing something wrong?

Share this post


Link to post
Share on other sites
That's because you're creating an image every time you draw to the screen.

Create the image outside of the paint method, like in the constructor. If the component is resizable, instead check in the paint method to make sure the image is null or a different size than the component before creating a new one.

You can also use java.awt.image.BufferedImage.

Share this post


Link to post
Share on other sites


And to add a bit of information still in addition to the previous posts, it is not possible to run the same Java applications on every Java runtime environment. For instance, Jave Mobile Edition is different than that of the desktop version. You have to modify your code somewhat or the thing you are trying to do is impossile all together. Also different handsets have different features, different bugs and different amount of resources.

I have written .NET, .NET Compact Framework, Symbian (Series 60), Palm OS and also J2ME applications and my experience is that .NET and .NET CF are very close to each other. In CF there are more static methods and thread handling if a bit different, but otherwise teh APIs are consistent. In Windows CE phones there aren't all the APIs or one have to resort to platform invoke (P/Invoke) to make Win32 calls, but otherwise quite similar.

Share this post


Link to post
Share on other sites
Quote:
That's because you're creating an image every time you draw to the screen.


no i dont. I create an image whenever my screen shifts, then draw stuff on it. So the image does not change unless the screen shifts. . .
And im not trying to make my game work on a phone, or hand-held or any other stuff.

Few more problems:
When i loaded all the game images, and whem i try to draw them on the screen, the first time they kinda flicker. (kinda annoying)
In my game whenever screen shifts, the background changes solor. like this:

back_col=new Color(x,y,z);
setBackground(back_col);

This too flickers like ugly . . .

Sometimes my game runs at 30% cpu, other times at 7%. Sometimes faster, other times slower (on the same computer). Whats going on?

Share this post


Link to post
Share on other sites
First I would like to ask a few questions:
- Is this your first attempt at making a game?
- Is java your first language, if not what was?
- What IDE (Code Editor) are you using?
- Are you using swing or awt or swt components like (JFrame, JPanel, or Frame, Panel)?
- My last question is how many things are you attempting to draw per frame?

Now Lets see if I can help you out from what I have gathered so far.
Quote:
Original post by alexxzius
Quote:
That's because you're creating an image every time you draw to the screen.


no i dont. I create an image whenever my screen shifts, then draw stuff on it. So the image does not change unless the screen shifts. . .
And im not trying to make my game work on a phone, or hand-held or any other stuff.

Few more problems:
When i loaded all the game images, and whem i try to draw them on the screen, the first time they kinda flicker. (kinda annoying)
In my game whenever screen shifts, the background changes solor. like this:

back_col=new Color(x,y,z);
setBackground(back_col);

This too flickers like ugly . . .

Sometimes my game runs at 30% cpu, other times at 7%. Sometimes faster, other times slower (on the same computer). Whats going on?


The flickering problem can be caused by two things, one you are calling paint or repaint at a set rate. Second which is the most probable case is that you are not drawing to a back buffer when you draw something. The common technic to reduce flickering effects is to create an image the same size as your screen and to draw to that first then once ALL your drawing is finished you draw that image to the screen in one go, almost like a movie only you are creating every frame at run time.

I have a short example of this on my blog with example code that you can use:
Double Buffering and Timed Rendering
Source files are available at the bottom of the post.

Your variable CPU usage is do mostly to events that are being thrown and processed. when your CPU usage is at 7% the application is most likely idling and waiting for new events, like moving the mouse across the screen or clicking furiously because its not doing what you want, moving the window, resizing the window, moving another window over top yours. Which may cause your application to need more time to process these events.


Something to note it doesn't matter how fast your are drawing your scene as long as it is over 30 frames a second noone will be able to tell the difference. The one thing that your game should spend the most time on is updating the objects you have on screen and of course your collision detection. Which makes sense since these are what take up the majority of time in Games is the collision detection and updating of the objects.

Time needed
collision detection - most
rendering - second most
updating - want this to run as many times per frame as possible (or about equals to rendering)
event handling - should be as quick as possible

Drawing your circles, rectangles, and lines to an image and then just drawing the image is a good idea, I've used it a couple times myself works like a charm. The only thing that you do have to remember is that you only need to draw it to an image once unless it changes in appearance. If nothing changes but its position on screen there is no sense in drawing it over again. So if by screen shifts you mean moves position or resizes then you shouldn't not be creating a new image but only moving or resizing the current image.

Moving is simple
Resizing without recreating the image is also simple, there is a Graphics.draw method which allows you to specify the height and width of the rectangle in the image you are drawing to, thus it will be resized to the height and width specified.

Hope this helps! Any more questions please feel free to ask.

Share this post


Link to post
Share on other sites
well, for starters, my game is one single 1900-line 80KB java file (61KB class file), with about 200 variables, 20 arrays and 30 functions. (ok, i know that most programmers preach about splitting the program into multiple files, but i tried it once didnt work for me so i never tried to make another multifile game again). U dont think that this may cause inconsistency in performance or flickering and other stuff? I made a few games before (in GameMaker). So i decided to make games in a more civilized language. Basicly Java appealed to me the most since it didnt look like it was written by a neanderthal (like C/C++ Allegro). C was my native language, but i couldnt do more with it except some ugly text games. Im using JCreator 4.00 LE (i like the bluish-purplish look of it).
Here is the heading of my game:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.AffineTransform;
public class motherload extends Applet implements Runnable{
...

In my game i draw 192 tiles (like i said), the digger(character) which can be in 5 modes (~3 frames for each mode), the score bar, and about a dozen other things that are sometimes drawn. Im not using JApplet or JFrame (is it better or faster?).
Quote:
The flickering problem can be caused by two things, one you are calling paint or repaint at a set rate.

Huh? So my game should run at variable rate? (like sleep for 30 ms one time and 100 ms another time?)
And I know about Double Buffering (Everyone whos remotely into Java game programming knows that he should implement Double Buffering even before he gets JDK ;). So it gotta be something else that flickers. I tried changing the background color in the update event, in the draw event, in various places, it still flickers.
The first time the images flicker i think has to do something with BufferedImage (but im not sure). Like the first time i enter the shop and i have 56 images in a grid 7 x 8, and it takes like 3 seconds for all of the to appear (they appear one after another). The second time i enter the shop, they appear simultaneously.
Whats the purpose of Timer and TimerTask?
Ok, im not resizing my window or doing anyhting crazy. I just open the html page with my applet (in the same browser), play the game (normally) and my cpu is 30%. Next day i do the same (without changing the source code) and my CPU is 7% and runs about 50% faster.
Few more questions (about a the self-absorbed world of java)
1. Ok, so i save my game info into a text file. Since i have 40 different tiles i write them as an encoded characters (most of them are the funny looking ones that are 128-256). And java thinks that im crazy or something and changes many of them into ? marks, but when the info is loaded back it treats ? as regular question marks and i get a bunch of exceptions and garbage. I changed the encoding into normal char so it works fine, but would like to know y it cant handle those ones.
2. Ok, so i jar my image folder and run the applet. But some of the images are not showing. Turns out those images had their extensions changed from .png to .PNG. So i have to go back and modify the loading function in my source code.
3. Ok, so i add one line to my source code (something harmless like x++), compile, jar, jarsign, and my JAR size increases by 300KB. Turns out that
its the thumbs database file that increased. What is its purpose? Will it do anything to my game if i just delete it from the jar?

Thanx for reading. ;)
Here is my game http://www.4shared.com/file/20348753/444ecaf3/Motherload.html
See, it flickers when the screen changes... (it dont flicker if i dont change background color)
another question: When i drawString() on my applet, the tabs and newlines dont show.

Share this post


Link to post
Share on other sites
Hi,

I was able to run your game and I observed no flickering, so I am wondering if others observe the same!

Quote:
Original post by alexxzius
Few more questions (about a the self-absorbed world of java)
1. Ok, so i save my game info into a text file. Since i have 40 different tiles i write them as an encoded characters (most of them are the funny looking ones that are 128-256). And java thinks that im crazy or something and changes many of them into ? marks, but when the info is loaded back it treats ? as regular question marks and i get a bunch of exceptions and garbage. I changed the encoding into normal char so it works fine, but would like to know y it cant handle those ones.
2. Ok, so i jar my image folder and run the applet. But some of the images are not showing. Turns out those images had their extensions changed from .png to .PNG. So i have to go back and modify the loading function in my source code.
3. Ok, so i add one line to my source code (something harmless like x++), compile, jar, jarsign, and my JAR size increases by 300KB. Turns out that
its the thumbs database file that increased. What is its purpose? Will it do anything to my game if i just delete it from the jar?

1. I'm not sure but it may have something to do with the way you are writing the data to file. Maybe some else have more expertise in this area, I for one have never had that problem.
2. Window's file system in not case sensitive so all your files will be converted to upper case that is why they changed. Its a good idea to keep all your file extensions in the same case and to use that case when loading the files.
3. The thumbs.db files or thumbs database file is created by windows when you look at a directory using the thumbnails viewing option in the explorer window. It is safe to delete. I believe it is used for quicker loading of folders with images when viewing the folder with "thumbnails" or "filmstrip". You can turn this feature in windows off by going to tools -> folder options -> view (tab) -> do not cache thumbnails (checkbox) that should save you from deleting it every time you want to jar.
4. drawString will not recognize newlines so you'll have to split them up using String.split and then draw each line a distance apart. Or you can use a JLabel or Label component settings its containing components layout to null and placing the component wherever you want it to be. If tabs are not working then you could substitute "\t" characters for " ".

NOTE: also you can use basic HTML in JLabel but you need to make sure that <html> and </html> are surrounding your string first before you can use them.

Share this post


Link to post
Share on other sites
u didnt see no flickering at all? Must be my java platform (like u said no 2 are alike lol)

1. this is what i use to write to a text file.
PrintStream file=new PrintStream(new FileOutputStream(file1));

2. all my image files have extension .png (in lowercase) before jaring. After, only one changes to .PNG ;(

One more question (already asked it with no success): What filename can i use so that i can read to and write to a file that is in the same directory as my JAR?
What i tried:
File file=new File(System.getProperty("user.home"),"file.txt");

It writes and reads from the same file located at "C:\Documents and Settings\LocalUser".
File file=new File("file.txt");

It writes a file to the desktop and tries to read a file from inside the JAR (obviosly 2 different files are used).


Share this post


Link to post
Share on other sites
File file=new File(System.getProperty("user.dir"),"file.txt");

Use user.dir instead of user.home. user.dir is the directory where the program was started from.

Share this post


Link to post
Share on other sites
;(
user.dir creates a text file on the desktop and the JAR is located at
C:\Documents and Settings\LocalUser\Java\jdk6\bin (a different location than the desktop).

Share this post


Link to post
Share on other sites
Run this test:

public class Test {
public static void main(String[] args) {
Enumeration en = System.getProperties().propertyNames();
while(en.hasMoreElements()) {
String key = (String)en.nextElement();
System.out.println(key + " = " + System.getProperty(key));
}
}
}



Just to double check what user.dir gives you. Every computer that I try it on gives me the location that the jar was started from.

Also don't forget that if you run it from a shortcut on the desktop, then the start location is the desktop. You have to set the "Start in" option of the properties of the shortcut to change where it starts up from.

Share this post


Link to post
Share on other sites
C:\Documents and Settings\LocalUser\Java\jdk6\bin\applc\Test.java:3: cannot find symbol
symbol : class Enumeration
location: class Test
Enumeration en = System.getProperties().propertyNames();
^
1 error

Process completed.



Share this post


Link to post
Share on other sites
nevermind. Forgot to import java.util.*;
--------------------Configuration: <Default>--------------------
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Documents and Settings\PolyUser\Java\jdk6\jre\bin
java.vm.version = 1.6.0-b105
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = Service Pack 1
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\Documents and Settings\PolyUser\Java\jdk6\bin\applc
java.runtime.version = 1.6.0-b105
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\endorsed
os.arch = x86
java.io.tmpdir = C:\DOCUME~1\PolyUser\LOCALS~1\Templine.separator =

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =
os.name = Windows XP
sun.jnu.encoding = Cp1252
java.library.path = C:\Documents and Settings\PolyUser\Java\jdk6\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\System32;C:\WINDOWS;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\Downloaded Program Files;C:\MATLAB7\bin\win32;C:\Program Files\Common Files\Autodesk Shared\;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Common Files\GTK\2.0\bin;C:\TCWIN45\BIN
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot Client Compiler
os.version = 5.1
user.home = C:\Documents and Settings\PolyUser
user.timezone =
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.6
user.name = PolyUser
java.class.path = C:\Documents and Settings\PolyUser\Java\jdk6\bin\applc;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\rt.jar;C:\Documents and Settings\PolyUser\Java\jdk6\lib\dt.jar;C:\Documents and Settings\PolyUser\Java\jdk6\lib\tools.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext\dnsns.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext\localedata.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext\sunjce_provider.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext\sunmscapi.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext\sunpkcs11.jar
java.vm.specification.version = 1.0
sun.arch.data.model = 32
java.home = C:\Documents and Settings\PolyUser\Java\jdk6\jre
java.specification.vendor = Sun Microsystems Inc.
user.language = en
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.6.0
java.ext.dirs = C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\resources.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\rt.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\sunrsasign.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\jsse.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\jce.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\lib\charsets.jar;C:\Documents and Settings\PolyUser\Java\jdk6\jre\classes
java.vendor = Sun Microsystems Inc.
file.separator = java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeLittle
sun.desktop = windows
sun.cpu.isalist = pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

Process completed.

Share this post


Link to post
Share on other sites
Hey guys,

If you are looking for the location of the jar I usually do the following:

File file = new File(""); //this will give you the current running directory path.

Loading Resources from within a jar file.
Then you can append the jar name which shouldn't change but you never know so this method isn't the most stable for loading resources from within a jar but it will help you access files within the jar by doing the following:

URL url = new URL( "jar:file:///" + file.getAbsolutePath().replaceAll(" ","%20") + jarName + "!" + filepathWithinJar );

The jarName should include the extension ".jar". But that is for reading files from within a jar file. The getResource will only work if the files you are trying to access are within the same directory as all your .class files since the ClassLoader uses those locations to check for resource files. The "jar:" is a protocol same with the "file:///" which can be replaced with "http://" if the file or jar is located on the inernet. The filepathWithinJar could be something like "/images/pic.PNG" or "/map.dat". If your using an applet you can use the Applet.getCodeBase() function to get the absolute path of the jar file.

Share this post


Link to post
Share on other sites
i dont think thats it.
I wanna read and write from the same file, and since u cant write to inside the JAR, u dont wanna read from the JAR. Plus i didnt understand half of what u said since im a newb. And i already signed my applet so i would like not to use URLs.

Share this post


Link to post
Share on other sites
Hey,

Sorry bout all the dribble about reading from jar files.

Your looking to do something like this then:


File file = new File("file.txt");
try {
PrintWriter pw = new PrintWriter( new FileOutputStream(file) );
pw.println("Hello World!");
pw.flush();
pw.close();

BufferedReader buffr = new BufferdReader( new FileReader(file) );
System.out.println(buffr.readLine());
buffr.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Test that out, I don't have a signed applet to make sure that this works but it should create the "file.txt" in the directory of the jar file. I'm not sure what path you will get when running this from an applet on the web though. I'll have to test that out later. If you've already tried this then let me know and see if you can upload it to the web and see what path (new File("")).getAbsolutePath() will return.

Share this post


Link to post
Share on other sites
;(
no, that still writes and reads from a file on the desktop.
And getAbsolutePath returns C:\Documents and Settings\LocalUser\Desktop

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement