Archive

Posts Tagged ‘text file’

JAVA Check To See If A File Already Exists

February 5, 2009 Leave a comment

How to check if a file already exists.

String file = “c:/file.csv”;

File f = new File(file);
if(f.exists()){
// code if file exists
}else{
// code if file doesn’t esist
}

The following example checks to see if the file exists, then asks the user if they want to overwrite it.
If the users selects yes, then the original file is deleted.

String file = “c:/file.csv”;

File f = new File(file);
if(f.exists()){

Object[] options = {“Yes”,
“No”,
“Cancel”};
int n = JOptionPane.showOptionDialog(null,
“File aready exists.\n”
+”Overwrite existing file?”,
“Warning”,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[2]);

if(n == 0){
try{
f.delete();
}catch(Exception e){
JOptionPane.showMessageDialog(null, “Error deleting file.\nClose the file if it is open.”);
return;
}
}
else{
return;
}

}

// Code to write out to the file, now the original has been deleted.




Categories: Java Tags: , ,

JAVA – How To APPEND To A Flat File (CSV, TEXT etc.)

February 4, 2009 Leave a comment

Appending to a file.

The following example will APPEND the text “More Sample Text” to c:/test.csv.
If test.csv doesn’t already exist then it will be created

String fileName = “c:/test.csv”;
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName , true));
out.write(“More Sample Text”);
out.close();
} catch (IOException e) {
}

Categories: Java Tags: , ,

How To Write To A Flat File (CSV, TEXT etc.)

February 4, 2009 Leave a comment

Writing to a file.

The following example will write the text “Sample Text” to c:/test.csv.
If test.csv doesn’t already exist then it will be created

String fileName = “c:/test.csv”;
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(“Sample Text”);
out.close();
} catch (IOException e) {
}

Categories: Java Tags: , ,
Follow

Get every new post delivered to your Inbox.