Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Class File and it's constructors

Status
Not open for further replies.

jisoo22

Programmer
Apr 30, 2001
277
US
Hello all,

I have a small program that has a method which uses the File class and it's exists() method. Unfortunately I think I'm constructing it wrong or something because I get a compile-time error saying that my constructor is an invalid statement. Can someone tell me the correct way to do it? My snippet of code is below so you can kind of see what I'm attempting to do. It takes in a file name (i.e. "temp.txt") and checks to see if it exists or not.

Thanks,
Jisoo22

Code:
import java.io.*;

public class simModel_2_1 {

	public static void main (String args[])

	{
          String fileName = "world.txt";
          fileName = checkReadFile(fileName, args);
          System.out.println(fileName);//debugging

	}

	public static String checkReadFile(String file, String [] args)

	{
		String temp;
		String str;

		if (str.length() > 0)
		{
			temp = str;
		}
		else
		{
			temp = file;
		}


		while (temp.equalsIgnoreCase("q") == false)

			File f = new File(temp);

			if(f.exists() == true)
			{

				return temp;

			}
			else
			{
				System.out.println("The simulation data file " + temp +
								   "cannot be read.");
				System.out.println("Enter a new file name or 'Q' to quit: ");
				str = Keyboard.readString();
			}
	}//checkReadFile
}//class simModel_2_1
[code]
 
I hope this will answer you question. It looks like you are doing a couple things wrong. First, when you want to call a static method on a class you must call ClassName.theMethod() or create an instance of the class and then call a method. If you want to open a file to read the best thing to do is to create a FileInputStream and pass it the path of the file you wish to open. If all you care about is whether the file exist try opening and when the JVM throws a FileNotFoundException you will know the file is not there. It is a checked exception and java will force you to handle it. Hope this helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top