0

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 } } 
4
  • 1
    I can't see the part that writes to a file in your code, but to check if a file or folder exists you need to use a File object which has an exists method Commented Nov 2, 2013 at 11:32
  • @Richard Tingle How exactly I can convert from Formatter to file object ? Thanks Commented Nov 2, 2013 at 11:41
  • 1
    See sumitb's answer which solves that. Is this program going to be windows or for all systems (always best), if all syatems beware that "/" is only the folder separator in windows Commented Nov 2, 2013 at 11:43
  • 1
    See here for an assortment of non system specific separators, including path seporator Commented Nov 2, 2013 at 11:45

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.