Reputation: 953
I am creating java project for my school, but now I am stuck here.
I want to create programm that creates .txt file and write my input from keyboard into it. But before that it checks if that file exists already. So the programm wouldn't create new file with the same name, but it would add that input to previusly inserted data.
In some words each time I run that programm it can add information to that .txt file. At this moment everything works fine but except checking if that file exists already. I tried to add exists(); but without success.
I am begginer at this so please give me a tip not all solution :) Thanks in advance !
code
private Formatter output; //object
public static String user_name() {
String user_name=System.getProperty("user.name");
return user_name;
};
public void openFile(){
try {
output = new Formatter(user_name()+".txt"); //here I tried to add exists() method to check if the file exists already. but it responded //with undefined method error.
}
catch ( SecurityException securityException )
{
System.err.println("Jums nav atļauja rediģēt šo failu");
System.exit(1); //izejama no programmas
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.print("Kļūda atverot failu");
System.exit(1); //izejama no programmas
}
}
Upvotes: 0
Views: 274
Reputation: 990
Use a File object for this task.
File f = new File("YourPathHere");
Once the you have this file object you can use exists function to check if the file exists or not
f.exists() //returns true if mentioned file exists else return false
Afterwards if you want to add the content to the existing file (technically called as append operation), you can tell the FileWriter Object to create stream to the file in append mode.
output = new BufferedWriter(new FileWriter(yourFileName, true)); //second argument true state that file should be opened in append mode
Upvotes: 2