File IO problem

M

Mauro Iotti

I need some help with a quite simple (not for me) problem...
I'm working with JBuilder and I wanna check if a file exists or not.
If not I wanna create it and then write some data in it, if yes I wanna
append the data.

Can someone help me?
Thank you!!

-PK
 
M

Michael Borgwardt

Mauro said:
I need some help with a quite simple (not for me) problem...
I'm working with JBuilder and I wanna check if a file exists or not.
If not I wanna create it and then write some data in it, if yes I wanna
append the data.

Read the API: http://java.sun.com/j2se/1.4.1/docs/api/index.html

In this case, specifically that of the java.io.File class for testing existence
of files and the java.io.FileWriter and java.io.FileOutputStream classes
for writing to files. Creation is implicit, appending an option.
 
V

VisionSet

Mauro Iotti said:
I need some help with a quite simple (not for me) problem...
I'm working with JBuilder and I wanna check if a file exists or not.
If not I wanna create it and then write some data in it, if yes I wanna
append the data.

Can someone help me?
Thank you!!

And please don't multi post!!
 
J

Joe55

Here is a code snippet, which I hope will help you:

try{

myFile = new File(sDirectory);

if (myFile.exists()){

//append the text to the existing
//use the constructor with the second parameter for append = true
fw = new FileWriter(sDirectory, true);
fw.write("file did already exist");
fw.close();

}else{

fw = new FileWriter(sDirectory);
fw.write("Here is some text");

//close the FileWriter
fw.close();
}
}catch (IOException e) {
System.out.println("Error writing to " + sDirectory);
}
 
J

Joe55

Here is a code snippet which I hope will help you:

//create a file object with the directory of the file
String sDirectory = "c:\\SampleDirectory\\Sample.txt";
File myFile;
FileWriter fw;

try{

myFile = new File(sDirectory);

if (myFile.exists()){

//append the text to the existing
//use the constructor with the second parameter for append = true
fw = new FileWriter(sDirectory, true);
fw.write("file did already exist");
fw.close();

}else{

fw = new FileWriter(sDirectory);
fw.write("Here is some text");

//close the FileWriter
fw.close();
}
}catch (IOException e) {
System.out.println("Error writing to " + sDirectory);
}
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top