Absolute path / creating FileWriter-object

J

Jesper Sahner

Hi!

I am creating a FileWriter-object in the following way:

FileWriter file = new FileWriter("myfile.txt");

The file "myfile.txt" is then placed in the directory from where Java
is called, in my setup C:\Program Files\NetBeans 3.6

However I want to place the file "myfile.txt" in the same directory
(package) as the .class-file in which the FileWriter-object is
created.

How do I do this?

Regards,
Jesper
 
O

Oscar kind

Jesper Sahner said:
FileWriter file = new FileWriter("myfile.txt");

The file "myfile.txt" is then placed in the directory from where Java
is called, in my setup C:\Program Files\NetBeans 3.6

However I want to place the file "myfile.txt" in the same directory
(package) as the .class-file in which the FileWriter-object is
created.

How do I do this?

You don't. At least not in a clean way.

You may try to find the part of the classpath where your class resides
(for example "."), and select the correct directory based on the package
name.

This "solution" will come crashing down however, if you:
- package the application in a .jar file, or
- use an URLClassloader, or
- use any other method where classes are not available in an unpacked
directory structure.
 
A

Andrew Thompson

However I want to place the file "myfile.txt" in the same directory
(package) as the .class-file in which the FileWriter-object is
created.

How do I do this?

*Why* do you want to do that? (See Oscar's answer)

It is generally better to put the file inside a known location
(sub directroy, whatever..) of "user.home".
 
Joined
Dec 11, 2009
Messages
1
Reaction score
0
You can do this to create a file in a specific directory

BufferedWriter out = new BufferedWriter(new FileWriter(directoryPath+folderSeperator+"index.html"));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top