-2

I'm trying to make a method that gets the name of a file, and checks if it exists. If it does exist, I want to add to it. If it doesn't exist I want to create it and then add to it. The first problem I'm having is with checking if it exists. I have if(Results.exists == false) to check if it exists, where "Results" is a string that contains the name of the file and ends in .txt (eg "PremiershipResults.txt"), but this keeps giving me an error: "cannot find symbol". The other problem that I'm having is that I can't figure out how to just create a file if needs be, and also how to just add to a file without overwriting the existing file's contents. If anyone could offer any suggestions, I'd really appreciate it

Robert
  • 15
  • 1
  • 7
  • Read this: [PrintWriter to append data if file exist](http://stackoverflow.com/q/24982744). You don't have to check if the file exists or not, the `PrintWriter` will do that. And a `String` is not a `File`, it cannot check if something like a file exists, therefore there is no `#exists` method available. – Tom Mar 10 '15 at 21:28

1 Answers1

0

I assume that, since the question is tagged with "Java" that you're trying to do this in the Java programming language. If this is not the case, then this answer, of course, won't apply, and you'll have to clarify the question on this point.

In the Java JDK API, there is, indeed, a method, File.exists(), which will indicate, via its boolean return value whether or not the file exists. However, this is a method on a File object, not a String. Furthermore, if this is Java, note that you needn't compare a boolean to false; just use a not operator, as below.

String filename = "PremiershipResults.txt";
File fileref = new File(filename);
if (!fileref.exists()) {
    // file does not exist (note ! operator)
    // so go ahead and create it
}
else {
    // use the existing file
}

Note, too, that if all that you really want to do is write to the end of the file if it already exists, you can open the file using the java.io.FileOutputStream(File f, boolean append) constructor, or the equivalent FileWriter constructor for a text file.

See the official API documentation for these classes at http://docs.oracle.com/javase/8/docs/api/java/io/package-frame.html for the specifics.

So, your code would look something like the following.

Jerry Oberle
  • 194
  • 1
  • 1
  • 7